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行,记录日志。

就是这么的简单!

 

posted on   hz_pythoner  阅读(4111)  评论(0编辑  收藏  举报

编辑推荐:
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
阅读排行:
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析

导航

< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10
点击右上角即可分享
微信分享提示