Reputation: 3423
I have a logger set up with two handlers - one to console and one a rotated file. I set each individual handlers with their own log level. The idea is that important messages are available on the console, while the lower level stuff goes to the file in case I need to do further troubleshooting.
My config file looks like this:
[loggers]
keys=root
[handlers]
keys=consoleHandler,rotateFileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,rotateFileHandler
qualname=MyApplication
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=ERROR
formatter=simpleFormatter
args=(sys.stdout,)
[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=INFO
formatter=simpleFormatter
args=('TESTLOG.log', 'a', 100000, 5, 'utf8')
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
Is there a way to dynamically change (and then reset) the log level for an individual handler? I have attempted to do this, but it fails because logger
is, well, the logger and not the handler. It is also already set to DEBUG
, it's the handlers that are set at higher levels.
import logging
import logging.config
logging.config.fileConfig('logging.config', disable_existing_loggers=False)
logger = logging.getLogger('TestLog')
def main():
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
# Reset log level to debug temporarily
logger.setLevel(logging.DEBUG)
logger.debug('This message appears if level was reset to DEBUG')
if __name__ == '__main__':
main()
My goal is to be able to set the console to a lower level (ie. logging.DEBUG
for a period of time and then change it back, either by saving the previous level before the change is executed or explicitly resetting it). I don't want to touch the other handlers when I do this though.
How do I change the handler log level dynamically?
Upvotes: 3
Views: 6863
Reputation: 21
I know this is old, but I'd thought I'd share that if you'd want to change a few handlers at one time you could search all handlers associated with that particular logger like this
for handlers in logger.handlers:
if type(handlers) == logging.FileHandler:
if boolcheck():
handlers.setLevel(logging.DEBUG)
else:
handlers.setLevel(logging.INFO)
Upvotes: 2
Reputation: 1123400
You'd have to traverse to the specific handler:
console_handler = logging.getLogger().handlers[0]
old_level = console_handler.level
console_handler.setLevel(logging.DEBUG)
The index matches the order from the handlers
in your logging configuration (any previous handlers on a given logger are cleared whet the config is loaded).
Upvotes: 4