Why can't I change the level of python logger?

Viewed 878

I am trying to change the loglevel of a python logger. But it does not seem to work:

import logging

#50 CRITICAL
#40 ERROR
#30 WARNING <-- default
#20 INFO
#10 DEBUG
# 0 NOTSET 

logger = logging.getLogger('a')
logger.setLevel(logging.DEBUG)
print('log level', logger.getEffectiveLevel())
logger.debug('Debug') # 10
logger.info('Info') # 20
logger.warning('Warning') # 30
logger.error('Error') # 40

The output is:

log level 10
Warning
Error

But should be:

log level 10
Debug
Info
Warning
Error

Why is that and what did I do wrong?

3 Answers

The problem is that the default logging handler handles only the default logging levels. You have to add a logging handler that does the actual logging. If you need just console logging, you could use:

logger = logging.getLogger('a')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
...

This gets you:

log level 10
Debug
Info
Warning
Error

logging.basicConfig() adds a handler with some basic formatting, but usually you will define your own format for logging.

One way to solve this is to set the basic config before logging the messages. Like this:

logging.basicConfig()

Although you've set the level of the logger, the message has to pass through a handler which has a log level also. The rule is that the most restrictive log level wins. There are several solutions. Broadly you can use basicConfig to setup the logging root and it will be inherited by child loggers like "a". Or set a handler for "a".

import logging

#50 CRITICAL
#40 ERROR
#30 WARNING <-- default
#20 INFO
#10 DEBUG
# 0 NOTSET 

# option - set a basic config for root logger and its descendents
#logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('a')
logger.setLevel(logging.DEBUG)

# option = create a handler for this logger
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

print('log level', logger.getEffectiveLevel())
logger.debug('Debug') # 10
logger.info('Info') # 20
logger.warning('Warning') # 30
logger.error('Error') # 40
Related