使用 dictConfig 时命名记录器不写入

Named logger not writing when using 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)

main.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')

记录-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, 时,我看到了所有日志消息。

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

我需要做什么才能让指定的记录器工作?

默认情况下,dictConfig 方法会禁用所有现有的记录器。

您可以通过将具有 false 值的 disable_existing_loggers 键添加到 logging-config.json.

来更改此行为
{
  
  "logging": {
    "version": 1,
    "disable_existing_loggers": false,
    ...
  }
}