作为开发者,我们可以通过以下3种方式来配置logging:
1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数;
2)创建一个日志配置文件,然后使用fileConfig()函数来读取该文件的内容;
3)创建一个包含配置信息的dict,然后把它传递个dictConfig()函数;
需要说明的是,logging.basicConfig()也属于第一种方式,它只是对loggers, handlers和formatters的配置函数进行了封装。另外,第二种配置方式相对于第一种配置方式的优点在于,它将配置信息和代码进行了分离,这一方面降低了日志的维护成本,同时还使得非开发人员也能够去很容易地修改日志配置。
一、使用Python代码实现日志配置
代码如下:- # 创建一个日志器logger并设置其日志级别为DEBUG
- logger = logging.getLogger('simple_logger')
- logger.setLevel(logging.DEBUG)
- # 创建一个流处理器handler并设置其日志级别为DEBUG
- handler = logging.StreamHandler(sys.stdout)
- handler.setLevel(logging.DEBUG)
- # 创建一个格式器formatter并将其添加到处理器handler
- formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
- handler.setFormatter(formatter)
- # 为日志器logger添加上面创建的处理器handler
- logger.addHandler(handler)
- # 日志输出
- logger.debug('debug message')
- logger.info('info message')
- logger.warn('warn message')
- logger.error('error message')
- logger.critical('critical message')
复制代码 运行输出:- 2017-05-15 11:30:50,955 - simple_logger - DEBUG - debug message
- 2017-05-15 11:30:50,955 - simple_logger - INFO - info message
- 2017-05-15 11:30:50,955 - simple_logger - WARNING - warn message
- 2017-05-15 11:30:50,955 - simple_logger - ERROR - error message
- 2017-05-15 11:30:50,955 - simple_logger - CRITICAL - critical message
复制代码 二、使用配置文件和fileConfig()函数实现日志配置
现在我们通过配置文件的方式来实现与上面同样的功能:- # 读取日志配置文件内容
- logging.config.fileConfig('logging.conf')
- # 创建一个日志器logger
- logger = logging.getLogger('simpleExample')
- # 日志输出
- logger.debug('debug message')
- logger.info('info message')
- logger.warn('warn message')
- logger.error('error message')
- logger.critical('critical message')
- 配置文件logging.conf内容如下:
- [loggers]
- keys=root,simpleExample
- [handlers]
- keys=fileHandler,consoleHandler
- [formatters]
- keys=simpleFormatter
- [logger_root]
- level=DEBUG
- handlers=fileHandler
- [logger_simpleExample]
- level=DEBUG
- handlers=consoleHandler
- qualname=simpleExample
- propagate=0
- [handler_consoleHandler]
- class=StreamHandler
- args=(sys.stdout,)
- level=DEBUG
- formatter=simpleFormatter
- [handler_fileHandler]
- class=FileHandler
- args=('logging.log', 'a')
- level=ERROR
- formatter=simpleFormatter
- [formatter_simpleFormatter]
- format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
- datefmt=
复制代码 运行输出:- 2017-05-15 11:32:16,539 - simpleExample - DEBUG - debug message
- 2017-05-15 11:32:16,555 - simpleExample - INFO - info message
- 2017-05-15 11:32:16,555 - simpleExample - WARNING - warn message
- 2017-05-15 11:32:16,555 - simpleExample - ERROR - error message
- 2017-05-15 11:32:16,555 - simpleExample - CRITICAL - critical message
复制代码 1. 关于fileConfig()函数的说明:
该函数实际上是对configparser模块的封装,关于configparser模块的介绍请参考 |