使用 dictConfig 时如何重新配置​​记录器格式化程序

dan*_*ast 6 python logging python-2.7 python-3.4

我用来dictConfig设置日志记录。simpleFormatter我的要求之一是将格式化程序的默认转换器(我对所有处理程序使用单个格式化程序)更改为time.gmtime. 这将像这样完成:

formatter.converter = time.gmtime
Run Code Online (Sandbox Code Playgroud)

如果我有权访问格式化程序。但我不这样做,所以我无法更改默认转换器。我可以想到两种方法来做我想做的事:

  • dictConfig通过, 在部分中传递相关参数formatters(类似'converter': 'ext://time.gmtime')但我认为这个额外的参数不支持dictConfig
  • 执行以下操作后获取格式化程序dictConfig并手动应用配置:formatter.converter = time.gmtime。我不知道如何按名称获取格式化程序,也不知道它是否受支持,或者是否会绕过模块logging.config

在查看了日志记录模块的源代码后,我既没有找到示例,也没有找到文档,也没有找到实现此目的的方法。

有人设法formatter.converter使用 dictConfig 设置来设置吗?

Vin*_*jip 7

以下是如何执行此操作的示例:

import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    'handlers': {
        'console1': {
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        },
        'console2': {
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        },
    },
    'root': {
        'handlers': ['console1', 'console2'],
   }
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('Look out!')
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我得到:

2015-10-17 12:20:36,217 Look out!
2015-10-17 13:20:36,217 Look out!
Run Code Online (Sandbox Code Playgroud)

自定义实例化密钥的使用'()'记录开头的段落中All other keys ...