Python logging: Can I pass arguments to a custom handler in json config file

旧时模样 提交于 2019-12-24 06:07:04

问题


Ive read the docs, but did not find any mention of this. Is it possible to pass parameters to a custom logging.handler class inside a json configuration file?

"handlers": {
    "custom_handler": {
        "class": "logging.CustomHandler",
        "args": ['a', 'b'] # <------------------------            
        "level": "INFO",
        "formatter": "custom"
    }
},

Where the handler class definition is :

class CustomHandler(logging.Handler):
    def __init__(self, argA, argB):
        super().__init__()
        self.a = argA
        self.b = argB
    def emit(self, record):
        <Some code>

回答1:


Every key in the handler section that is not one of class, level, formatter or filters is passed to handler constructor as keyword argument. Example:

"handlers": {
    "custom_handler": {
        "class": "logging.CustomHandler",
        "level": "INFO",
        "formatter": "custom",
        "argA": "spam",
        "argB": "eggs"
    }
}

This also means that having a handler with a constructor arg named class, level, formatter or filters is a bad idea...

Source: Configuration dictionary schema.



来源:https://stackoverflow.com/questions/52423254/python-logging-can-i-pass-arguments-to-a-custom-handler-in-json-config-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!