今天用yaml文件寫了一下logging的配置,文件以下:python
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 backupCount: 20 encoding: utf8 error_file_handler: class: logging.handlers.RotatingFileHandler level: ERROR formatter: simple filename: errors.log maxBytes: 10485760 backupCount: 20 encoding: utf8 loggers: my_module: level: ERROR handlers: [console] propagate: no root: level: INFO handlers: [console, info_file_handler]
只是作個demo,因此寫的比較粗略,而後中間就是包含了formatter,handlers,並無使用filters,最終的效果是ERROR級別的信息將會在命令臺進行打印並寫入日誌文件當中。日誌
# -*- coding: utf-8 -*- import os import yaml import logging from logging import config as logger_config config_file = os.path.join(os.path.dirname(__file__), "config.yaml") if os.path.exists("mylog"): pass else: os.mkdir("mylog") with open(config_file, "rt") as stream: config = yaml.unsafe_load(stream.read()) logger_config.dictConfig(config) logger = logging.getLogger() if __name__ == "__main__": logger.error("This is a test error message for my first logger.")
運行這個命令就能夠看到相應的結果了。
code