Reputation: 3905
I have a logging
object that was initialised using logging.config.dictConfig(logging_conf_dict)
:
import logging.config
logging_conf_dict = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'console': {
'format': '%(asctime)s %(name)s %(levelname)s %(lineno)d %(message)s',
},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'console',
},
},
'loggers': {
# root logger
'': {
'level': 'INFO',
'handlers': ['console'],
},
}
}
logging.config.dictConfig(logging_conf_dict)
For testing purposes I am trying to do the operation in reverse. I want to get the configurations dict from a configured logging
object...
something like:
logging_conf_dict = logging.config.dump()
or
logging_conf_dict = get_configurationns(logging)
Is there a way to access the configurations dict of the logging
object as a dictionary
Upvotes: 3
Views: 602
Reputation: 4106
Unfortunately the original dict configuration is not persisted during the load of the configuration within the logging
module.
So your best bet might be creating your own custom parser which will retrieve available loggers and parse their handlers and formatters.
Something like this:
import logging
def parse_logging_dictconfig():
dict_config = {"loggers": {}}
level_name_map = {
logging.DEBUG: "DEBUG",
logging.INFO: "INFO",
# etc...
}
loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
for logger in loggers:
logger_config = {}
logger_config["level"] = level_name_map.get(logger.level)
logger_config["handlers"] = []
for handler in logger.handlers:
logger_config["handlers"].append(handler.name)
dict_config["loggers"][logger.name] = logger_config
return dict_config
The example is not complete, but based on that you can get the basic idea.
Upvotes: 3
Reputation: 4869
Unfortunately, that information is not stored. As you can see in the source code, https://github.com/python/cpython/blob/3.9/Lib/logging/config.py, logging.config.dictConfig
only stores the passed in config in a termporary dict which gets thrown away at the end of the function (starting line 805):
dictConfigClass = DictConfigurator
def dictConfig(config):
"""Configure logging using a dictionary."""
dictConfigClass(config).configure()
and looking at the configure
method, the dict is not stored there either.
I'm guessing the reason they do this is that dictConfig
is acting on global variables (the default logger).
Upvotes: 2