1

I am trying to write a logger in Python, but the .setLevel method seems to not care which logging level I pass to it. Here's a minimally reproducible example:

import logging

logger = logging.getLogger("test")
logger.setLevel(logging.DEBUG)

logger.debug("debug")
logger.info("info")
logger.warning("warning")
logger.error("error")
logger.critical("critical")

Output:

warning
error
critical

As shown, I've set the level of my logger object to DEBUG, and yet only messages with levels WARNING and above are emitted.

From the documentation of setLevel:

Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level.

In my code I've called setLevel to set the level of this specific logger object so it should have respected that level. Whats the explanation for this behaviour?

I've looked at the following stackoverflow questions and neither solutions apply to my case.

Python logger not respecting setLevel?

python logging: logger setLevel() is not enforced?

I'm using CPython 3.8.2

kwsp
  • 1,184
  • 7
  • 26

1 Answers1

3

Ah you hit the nail on the head without realizing:

unless a handler’s level has been set to a higher severity level than level.

The root logger is of level logging.WARNING and its default handler is what you're using with logger unless you specify otherwise by explicitly giving logger a handler.

Running logging.basicConfig() will create an explicit handler for the root logger, which doesn't have the same limitation as the root handler.

import logging
logger = logging.getLogger('test')
logger.setLevel(logging.DEBUG)

logger.debug('invisible')
logger.warning('visible')

logging.basicConfig()

logger.debug('visible')
logger.warning('visible')
Adam Smith
  • 52,157
  • 12
  • 73
  • 112