python的logging模塊之讀取yaml配置文件。

python的logging模塊是用來記錄應用程序的日誌的。關於logging模塊的介紹,我這裏不贅述,請參見其餘資料。這裏主要講講如何來讀取yaml配置文件進行定製化的日誌輸出。python

python要讀取yaml文件,就必須安裝擴展的模塊。oracle

那麼咱們就安裝相應模塊。spa

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]

配置文件關鍵點解釋:code

其實這個配置文件可讀性仍是很高的,沒有難點。就是設置相應的值。好比這裏建立了三個handler:console, info_file_handler, error_file_handler.orm

配置完yaml文件,就能夠在你的py文件裏使用它了。下面來舉例說明使用方法。對象

建立一個python文件"trylog.py"blog

 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。 ip

第15行,使用file類讀取yaml文件,得到文件對象。utf-8

第16行,使用yaml模塊中的方法,載入文件流。獲得配置信息,應該是一個字典。

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

第19行,建立logger對象。

第22行,記錄日誌。

就是這麼的簡單!

相關文章
相關標籤/搜索