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

时间:2023-03-09 09:33:41
python的logging模块之读取yaml配置文件。

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

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

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

pip install pyyaml

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

 version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(filename)s - %(levelname)s - %(message)s" handlers:
console:
class: logging.StreamHandler
level: ERROR
formatter: simple
stream: ext://sys.stdout info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: ./mylog/info.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8 error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: errors.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8 loggers:
my_module:
level: ERROR
handlers: [console]
propagate: no root:
level: INFO
handlers: [console, info_file_handler]

配置文件关键点解释:

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

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

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

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: hz_oracle import logging.config
import os
import yaml log_conf = './conf/ethan_conf.yaml'
if os.path.exists("mylog"):
pass
else:
os.mkdir('mylog') with file(log_conf, 'rt') as f:
config = yaml.safe_load(f.read()) logging.config.dictConfig(config)
logger = logging.getLogger() 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行,记录日志。

就是这么的简单!