如何正确配置“ dictConfig”以使用其他日志格式?

时间:2020-04-04 17:42:45

标签: python-3.x logging

我正在尝试使用dictConfig将记录器配置为使用其他格式,但是它似乎没有生效。以下是我的代码(我也同时尝试禁止导入模块的日志)-

import logging.config
import requests

logging.config.dictConfig({
    'version': 1,
    'disable_existing_loggers': True,
    'formatters':{'standard': { 'format': "[%(asctime)s] [%(levelname)8s] - %(message)s", 'datefmt':"%d-%b-%Y %I:%M:%S %p"}},
    'handlers': {'default': {'level': 'DEBUG', 'formatter': 'standard', 'class': 'logging.StreamHandler', 'stream': 'ext://sys.stdout'}},
    'loggers':{'__main__': {'handlers': ['default'], 'level': 'DEBUG', 'propagate': False }}
})

req = requests.get('https://www.google.com')

logging.debug("Only thing that should be printed")

输出-

DEBUG:root:Only thing that should be printed

预期产量-

[2020-04-04 22:46:24,866] [   DEBUG] - Only thing that should be printed

我从SO post中学到了如何使用dictConfig

1 个答案:

答案 0 :(得分:0)

如果您查看提到的帖子,您会发现自己忘了一行:)

Data

必须在记录器名称中使用点符号显式定义记录器层次结构。

使用log = logging.getLogger(__name__) log.debug("Only thing that should be printed") 时:

这意味着记录器名称跟踪程序包/模块的层次结构,并且 从直观上很明显,仅从记录器记录事件的位置 名称。

有关更多说明,文档非常漂亮{​​{3}}。

相关问题