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

标签 python python-2.7 logging python-logging

当我尝试使用命名记录器为每个模块编写日志时,我希望如果没有专门为命名记录器配置的处理程序,日志将传播到根记录器。这在我使用 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)

主要.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} 的处理程序”)。

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

最佳答案

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

您可以通过将具有 false 值的 disable_existing_loggers 键添加到 logging-config.json 来更改此行为。

{
  
  "logging": {
    "version": 1,
    "disable_existing_loggers": false,
    ...
  }
}

关于python - 使用 dictConfig 时命名记录器不写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65397003/

相关文章:

python - logging.config.dictConfig 似乎不起作用

python - Django React Nginx 服务管理静态文件

python - Pandas .agg 中的过滤计数

python - 使用 Django 进行 App Engine 模型过滤

python - 在Python中创建多个记录器到同一模块中的不同输出

mysql - 记录实时搜索未命中

python - 将 perl 翻译成 python——这一行是做什么的(类变量混淆)

Python:遍历列表项 x 次?

python - 从字典中的自定义函数访问值

logging - Glassfish 到系统日志