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行,記錄日志。

就是這么的簡單!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM