实用python

python之使用yaml文件配置logging日志

2020-10-10  本文已影响0人  _karen

test.yml文件
说明:

version: 1
# 将信息传播到配置文件的跟日志记录器中
disable_existing_loggers: False

formatters:
    simple:
        format: "%(asctime)s - %(filename)s -%(name)s -%(levelname)s - %(message)s"
handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple
        stream: ext://sys.stdout

    info_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: INFO
        formatter: simple
        filename: ./info.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8

    # error_file_handler:
        # class: logging.handlers.RotatingFileHandler
        # level: ERROR
        # formatter: simple
        # filename: ./info.log
        # maxBytes: 10485760 # 10MB
        # backupCount: 20
        # encoding: utf8

loggers:
    my_module:
        level: ERROR
        handlers: [console]
        # 打开日志记录器
        propagate: False

log:
    level: DEBUG
    handlers: [console, info_file_handler]

python文件

import logging
from logging import config
import yaml

with open("test.yml", 'r', encoding="utf-8")as f:
    logging_yaml = yaml.load(stream=f, Loader=yaml.FullLoader)
    # print(logging_yaml)
    # 配置logging日志:主要从文件中读取handler的配置、formatter(格式化日志样式)、logger记录器的配置
    logging.config.dictConfig(config=logging_yaml)
# 获取根记录器:配置信息从yaml文件中获取
log = logging.getLogger()
# 子记录器的名字与配置文件中loggers字段内的保持一致
my_module = logging.getLogger("my_module")
# print("rootlogger:", log.handlers)
# print("selflogger", my_module.handlers)
# print("子记录器与根记录器的handler是否相同:", root.handlers[0] == my_module.handlers[0])
my_module.error("DUBUG")
log.info("INFO日志输出")
log.error('ERROR日志输出')
log.debug("DEBUG日志输出")
上一篇下一篇

猜你喜欢

热点阅读