首页 > 文章列表 > python配置日志记录

python配置日志记录

python日志记录
126 2022-08-07

1、三种配置日志记录的方法

调用列出的配置方法显式创建记录器,处理器和格式化器。

创建日志配置文件并使用 fileConfig() 函数读取它。

创建配置信息字典并将其传递给 dictConfig() 函数。

2、实例

以下示例使用 Python 代码配置一个非常简单的记录器,一个控制台处理器和一个简单的格式化器:

import logging
 
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
 
# 创建控制台处理器并设置级别进行调试
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
 
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 
# add formatter to ch
ch.setFormatter(formatter)
 
# add ch to logger
logger.addHandler(ch)
 
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')