How to set the python logging class using dictConfig

Question:

I’m using a dictConfig to setup logging, for example like this:

LOGGING_CONF: typing.Dict[str, typing.Any] = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "default": {
            "format": "%(asctime)s %(levelname)s %(name)s %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "default",
            "stream": "ext://sys.stdout",
            "level": "DEBUG",
        },
    },
    "loggers": {
        "my_app": {
            "class": "my_app.logging.MyLogger",  <- Its about this line
            # "()": "my_app.logging.MyLogger",   <- also tried this without success
            "level": "DEBUG",
            "handlers": ["console"],
            "propagate": False,
        },
        "uvicorn": {
            "level": "DEBUG",
            "handlers": ["console"],
            "propagate": False,
        },
    },
}

def init_logging() -> None:
    logging.config.dictConfig(LOGGING_CONF)

My question is around the my_app logger which I want to use a custom logging class, which does certain things based on additional parameters (enrich with database model references for example).

This configuration above doesn’t raise any errors, but also the custom logging class is not used. Is there a way to configure a custom logging class using dictConfig?

Asked By: Daniel

||

Answers:

From the logging.config docs:

The schema supports user-defined objects for handlers, filters and formatters. (Loggers do not need to have different types for different instances, so there is no support in this configuration schema for user-defined logger classes.)

So no, you can’t do this with logging.config.dictConfig. As far as I can tell, the only way to set a logger class is with logging.setLoggerClass, which sets the class used for all new loggers.

Answered By: user2357112
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.