如何使用 pythons 日志记录配置将参数传递给自定义日志格式化程序?

How do I pass parameters to custom log formatters using pythons logging configuration?

在我的 python 项目中,我有一个自定义的日志格式化程序,我想在构建时将它传递给一个字符串,然后将其添加到它正在注销的消息中:

class MyCustomFormatter(logging.Formatter):
def __init__(self, *args, **kwargs):
    super(MyCustomFormatter, self).__init__(*args, **kwargs)

    print(f'configuring {args} {kwargs}')

    if 'constants' in kwargs:
        self.constants = kwargs.get('constants')

我正在使用 python 提供的 logging.yml 配置来配置我的日志记录:

version: 1
formatters:
    standardFormatter:
        class: MyCustomFormatter
        constants: "constants"
handlers:
    consoleHandler:
        class: logging.StreamHandler
        level: INFO
        formatter: standardFormatter
        stream: ext://sys.stdout
root:
    level: DEBUG
    handlers: [consoleHandler]

我期待 'constants' 在 kwargs 中传递给 MyCustomFormatter.init,但是 kwargs 似乎是空的。如何在日志记录配置中配置一个值并将其传递给我的格式化程序?

在日志字典中找到的未知键仅作为 kwargs 传递给处理程序的构造函数,或者在将 custom instantiation 与特殊的 () 键一起使用时。因此,在您的情况下,您需要像这样配置格式化程序:

formatters:
    standardFormatter:
        (): importpath.for.MyCustomFormatter
        constants: constants

我建议完全不要使用 dictConfig 并使用 fileConfig,这样可以更轻松地处理许多类似的特殊情况。