logging模块yaml配置

普通logging.conf配置

yaml文件配置logging.yaml

version: 1

disable_existing_loggers: False

formatters:
    simple:
        format: "%(asctime)s [%(name)s] [%(levelname)s] :%(levelno)s: %(message)s"
        datefmt: '%F %T'

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 #most 20 extensions
        encoding: utf8
    error_file_handler:
        class: logging.handlers.RotatingFileHandler
        level: ERROR
        formatter: simple
        filename: errors.log
        maxBytes: 10485760 # 10MB
        backupCount: 20
        encoding: utf8
root:
    level: INFO
    handlers: [console, info_file_handler]

使用yaml配置文件

# -*- coding=utf-8 -*-import os
import logging.config
import os
import yaml

def setup_logging(default_path='logging.yaml', default_level=logging.INFO):
    """
    Setup logging configuration
    """
    path = default_path
    if os.path.exists(path):
        with open(path, 'rt') as f:
            config = yaml.load(f.read())
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)
        print('the input path doesn\'t exist')


if '__main__' == __name__:
    setup_logging(default_path='logging.yaml')
    # 默认拿到root的logger
    logger = logging.getLogger()
    logging.info('jhaha', exc_info=True)

运行结果分别在log文件和控制台中输出

转自https://blog.csdn.net/a469357594/article/details/79024907

猜你喜欢

转载自blog.csdn.net/qq_15111861/article/details/81739875