python的logging模块之读取yaml配置文件。

python的logging模块是用来记录应用程序的日志的。关于logging模块的介绍,我这里不赘述,请参见其他资料。这里主要讲讲如何来读取yaml配置文件进行定制化的日志输出。

python要读取yaml文件,就必须安装扩展的模块。

那么我们就安装相应模块。

pip install pyyaml

yaml文件的格式有点类似于字典,但是它没有括号。接下来就定制一个logging的yaml配置文件。

 1 version: 1
 2 disable_existing_loggers: False
 3 formatters:
 4     simple:
 5         format: "%(asctime)s - %(filename)s - %(levelname)s - %(message)s"
 6 
 7 handlers:
 8     console:
 9         class: logging.StreamHandler
10         level: ERROR
11         formatter: simple
12         stream: ext://sys.stdout
13 
14     info_file_handler:
15         class: logging.handlers.RotatingFileHandler
16         level: INFO
17         formatter: simple
18         filename: ./mylog/info.log
19         maxBytes: 10485760 # 10MB
20         backupCount: 20
21         encoding: utf8
22 
23     error_file_handler:
24         class: logging.handlers.RotatingFileHandler
25         level: ERROR
26         formatter: simple
27         filename: errors.log
28         maxBytes: 10485760 # 10MB
29         backupCount: 20
30         encoding: utf8
31 
32 loggers:
33     my_module:
34         level: ERROR
35         handlers: [console]
36         propagate: no
37 
38 root:
39     level: INFO
40     handlers: [console, info_file_handler]

配置文件关键点解释:

其实这个配置文件可读性还是很高的,没有难点。就是设置相应的值。比如这里创建了三个handler:console, info_file_handler, error_file_handler.

配置完yaml文件,就可以在你的py文件里使用它了。下面来举例说明使用方法。

创建一个python文件"trylog.py"

 1 #!/usr/bin/env python  
 2 # -*- coding:utf-8 -*- 
 3 # Author: hz_oracle
 4 
 5 import logging.config
 6 import os
 7 import yaml
 8 
 9 log_conf = './conf/ethan_conf.yaml'
10 if os.path.exists("mylog"):
11     pass
12 else:
13     os.mkdir('mylog')
14 
15 with file(log_conf, 'rt') as f:
16     config = yaml.safe_load(f.read())
17 
18 logging.config.dictConfig(config)
19 logger = logging.getLogger()
20 
21 
22 logger.warning("This is a test error message for my first doing it")

配置文件的位置是./conf/ethan_conf.yaml。 

第15行,使用file类读取yaml文件,获得文件对象。

第16行,使用yaml模块中的方法,载入文件流。得到配置信息,应该是一个字典。

第18行,使用logging.config.dictConfig 读取配置

第19行,创建logger对象。

第22行,记录日志。

就是这么的简单!

原文地址:https://www.cnblogs.com/hzpythoner/p/7809963.html