在Python中设置记录日志可以通过以下几种方法:
1. 使用`logging.basicConfig`进行基本配置:
python
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s[%(levelname)s]%(message)s',
handlers=[logging.FileHandler('app.log'),
logging.StreamHandler()])
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
2. 使用`logging.getLogger`创建自定义的日志记录器,并添加处理器和格式化器:
python
import logging
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
3. 使用`logging.fileConfig`从配置文件加载日志设置:
python
import logging
logging.fileConfig('logging.conf')
logger = logging.getLogger()
logger.debug('Debug message from file config')
4. 使用`logging.dictConfig`从字典配置加载日志设置:
python
import logging
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'DEBUG',
'formatter': 'default',
'stream': 'ext://sys.stdout'
},
'file': {
'class': 'logging.FileHandler',
'level': 'DEBUG',
'formatter': 'default',
'filename': 'app.log'
}
},
'loggers': {
'': { root logger
'handlers': ['console', 'file'],
'level': 'DEBUG',
'propagate': False
}
}
}
logging.config(LOGGING_CONFIG)
logger = logging.getLogger()
logger.debug('Debug message from dict config')
以上示例展示了如何使用Python的`logging`模块进行日志记录配置。您可以根据需要选择不同的配置方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/39346.html