使用 dictConfig

问题描述

当我尝试为每个模块使用命名记录器编写日志时,如果没有专门为命名记录器配置的处理程序,我希望日志会传播到根记录器。这在我使用 basicConfig 时工作正常,但是当我使用 dictConfig 时,来自命名记录器的日志消息会被丢弃

如何让命名记录器正确写出日志消息?

foo.py

import logging

logger = logging.getLogger('foo')


def doFoo(text):
    logger.debug(text)
    logger.info(text)
    logger.warn(text)
    logger.error(text)

ma​​in.py

import json
import logging.config
import foo

# logging.basicConfig(level=logging.DEBUG) # works as expected with this
with open('logging-config.json') as f:
    config = json.load(f)
logging.config.dictConfig(config['logging'])
logging.info('starting')
foo.doFoo('this is a test')

logging-config.json

{
  "logging": {
    "version": 1,"formatters": {
      "standard": {
        "class": "logging.Formatter","datefmt": "%Y-%m-%d %H:%M:%S","format": "%(asctime)s %(name)s %(levelname)s: %(message)s"
      }
    },"handlers": {
      "stdout": {
        "class": "logging.StreamHandler","level": "INFO","formatter": "standard","stream": "ext://sys.stdout"
      }
    },"root": {
        "level": "INFO","handlers": ["stdout"]
    }
  }
}

当我使用 dictConfig 跑步时,我只能看到 root INFO: starting

当我使用 basicConfig, 运行时,我会看到所有日志消息。

我知道在调用配置日志记录之前创建了命名记录器(通过模块的导入执行),但是从一些测试中我看到记录器只会在使用之前丢弃日志消息 日志记录已配置(并将发出消息“找不到记录器 {name} 的处理程序”)。

我需要做什么才能让命名记录器工作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)