How can I modify a log handler?

I have logging set up to:

  1. Write everything with at least an INFO level to the console
  2. Write everything with at least a DEBUG level 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

comments

raylu
logger.handlers[0].setLevel('DEBUG')
nrogers64 [OP]

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

It's not a dictionary:

'handlers': ['console', 'file'],

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.