首页 > 编程 > Python > 正文

详解python之配置日志的几种方式

2020-02-16 01:33:42
字体:
来源:转载
供稿:网友

作为开发者,我们可以通过以下3中方式来配置logging:

1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数;

2)创建一个日志配置文件,然后使用fileConfig()函数来读取该文件的内容;

3)创建一个包含配置信息的dict,然后把它传递个dictConfig()函数;

需要说明的是,logging.basicConfig()也属于第一种方式,它只是对loggers, handlers和formatters的配置函数进行了封装。另外,第二种配置方式相对于第一种配置方式的优点在于,它将配置信息和代码进行了分离,这一方面降低了日志的维护成本,同时还使得非开发人员也能够去很容易地修改日志配置。

一、使用Python代码实现日志配置

代码如下:

# 创建一个日志器logger并设置其日志级别为DEBUGlogger = logging.getLogger('simple_logger')logger.setLevel(logging.DEBUG)# 创建一个流处理器handler并设置其日志级别为DEBUGhandler = logging.StreamHandler(sys.stdout)handler.setLevel(logging.DEBUG)# 创建一个格式器formatter并将其添加到处理器handlerformatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")handler.setFormatter(formatter)# 为日志器logger添加上面创建的处理器handlerlogger.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 message2017-05-15 11:30:50,955 - simple_logger - INFO - info message2017-05-15 11:30:50,955 - simple_logger - WARNING - warn message2017-05-15 11:30:50,955 - simple_logger - ERROR - error message2017-05-15 11:30:50,955 - simple_logger - CRITICAL - critical message

二、使用配置文件和fileConfig()函数实现日志配置

现在我们通过配置文件的方式来实现与上面同样的功能:

# 读取日志配置文件内容logging.config.fileConfig('logging.conf')# 创建一个日志器loggerlogger = 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=DEBUGhandlers=fileHandler[logger_simpleExample]level=DEBUGhandlers=consoleHandlerqualname=simpleExamplepropagate=0[handler_consoleHandler]class=StreamHandlerargs=(sys.stdout,)level=DEBUGformatter=simpleFormatter[handler_fileHandler]class=FileHandlerargs=('logging.log', 'a')level=ERRORformatter=simpleFormatter[formatter_simpleFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt=            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表