MichaelR
MichaelR

Reputation: 999

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

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>

Upvotes: 4

Views: 2911

Answers (1)

hoefling
hoefling

Reputation: 66261

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.

Upvotes: 8

Related Questions