How can I modify a log handler?
I have logging set up to:
- Write everything with at least an
INFOlevel to the console - Write everything with at least a
DEBUGlevel to a file
I'd like to update the console handler (#1 in the above list) on the fly to change the minimum level from INFO to DEBUG while still keeping the file logger. Here is my code:
import logging
from logging.config import dictConfig
logger = logging.getLogger('test_logger')
DEFAULT_LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/tmp/python_logging_test.log',
},
},
'loggers': {
'test_logger': {
'handlers': ['console', 'file'],
'level': 'DEBUG',
},
},
}
dictConfig(DEFAULT_LOGGING)
logger.debug('Debug message before logging changes')
logger.info('Info message before logging changes')
LOGGING_CHANGES = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
}
dictConfig(LOGGING_CHANGES)
logger.debug('Debug message after logging changes')
logger.info('Info message after logging changes')
This is the output I expect to get in my console:
Info message before logging changes
Debug message after logging changes
Info message after logging changes
This is the output I actually get in my console:
Info message before logging changes
Info message after logging changes
As you can see, it's as if my dictConfig(LOGGING_CHANGES) line isn't doing anything. My file handler is staying intact, though, which is what I want. So that's good. But I don't know why I'm not seeing Debug message after logging changes output to my console. Any suggestions?
3 comments · 100% upvoted · other discussions
nrogers64 [OP] 1 points · Sep 2016
Thank you! That worked. But is there a way to do it without knowing the index of the "console" handler? And how does your code work if dictionaries' ordering isn't guaranteed?
raylu 1 points · Sep 2016
It's not a dictionary:
You can also just iterate over the whole thing.
All in all, log4j was never a great library and porting all of its madness over to python results in not a great library. You can write the 3 things you need yourself without messing with
logging.