Python3的Logging模块支持以YAML配置文件形式导入日志配置,logging.yaml文件 内容类似于下面的形式

version: 1
formatters:
  common:
    format: "%(asctime)s - %(levelname)s - %(threadName)s - %(message)s"
    datefmt: "%Y/%m/%d %H:%M:%S"
  console:
    format: "%(asctime)s - %(levelname)s - %(pathname)s - %(message)s"
    datefmt: "%Y/%m/%d %H:%M:%S"
handlers:
  common:
    class: logging.handlers.TimedRotatingFileHandler
    formatter: common
    level: INFO
    when: D
    interval: 1
    encoding: utf8
    filename: "logs/running.log"
    backupCount: 7
  console:
    class : logging.StreamHandler
    formatter: console
    level   : INFO
    stream  : ext://sys.stdout
loggers:
  main.common:
    level: INFO
    handlers: [common]
root:
  level: DEBUG
  handlers: [console]

在项目入口 main.py文件 中用如下代码导入这个日志配置

import logging
import yaml
from logging import config

with open('logging.yaml', 'r', encoding='utf-8') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)
    logging.config.dictConfig(config)
logger = logging.getLogger('main.common')

这样非常方便我们配置不同环境下的日志配置,生产环境与测试环境打包不同的logging的文件即可以实现不同的日志输出效果

但上面的代码会引发一个问题,即如果handlers中指定的日志文件夹如果不存在就会抛出异常

所以需要在导入之前创建对应的文件夹,这个我遍寻了Logging的官方文档并没有找到,只能以手工方法创建,如果有官方配置方法还请不吝赐教

import logging
import yaml
from logging import config

with open('logging.yaml', 'r', encoding='utf-8') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)
    for key,value in config['handlers'].items():
        if value.get('filename'): 
            if not os.path.exists(os.path.dirname(value.get('filename'))):
                os.mkdir(os.path.dirname(value.get('filename')))
    logging.config.dictConfig(config)
logger = logging.getLogger('main.common')