0

While experimenting with python's logging module, I came across some unexpected behaviour. My guess is that this is due to my misunderstanding, rather than a bug, but I can't figure out what's wrong (and I've been careful to restart the python kernel before testing, to ensure that the root logger is only configured once.

import logging
logging.basicConfig(level=logging.CRITICAL)
logger1 = logging.getLogger(__name__)
logger1.debug("logger1 debug test")

As expected, the logging message is not output.

If I then change the level of the logger as follows:

logger1.setLevel('DEBUG')
logger1.debug("logger1 debug test")

I get the expected output:

DEBUG:__main__:logger1 debug test

However, when I now create a new logger object, it seems to have inherited the properties of logger1, rather than of root:

logger2 = logging.getLogger(__name__)
logger2.debug("logger2 debug test")

which produces:

DEBUG:__main__:logger2 debug test

Weirdly, logger2 still shows the root as the parent, yet shows a level of 10:

print(logger2.__dict__)

{'filters': [], 'name': '__main__', 'level': 10, 'parent': <RootLogger root (CRITICAL)>, 'propagate': True, 'handlers': [], 'disabled': False, '_cache': {10: True}, 'manager': <logging.Manager object at 0x00000265147F2B48>}

Can anyone please explain why logger2 isn't defaulting to a level of 0 (NOTSET)?

spacediver
  • 109
  • 1
  • 10
  • Check https://stackoverflow.com/questions/44783527/python-logger-level-inherited-from-root-set-to-warning-by-default – Abhinav Mathur Oct 20 '20 at 18:51
  • @AbhinavMathur If I'm understanding that question (and the answer), the issue there is that the user was unaware that the default (effective) level for all logger objects is the root level (i.e. the parent). My question is the opposite - I'm asking why the default (effective) level for logger2 is NOT the same as root – spacediver Oct 20 '20 at 19:01
  • Try ```logger2 = logging.getLogger()``` – Abhinav Mathur Oct 20 '20 at 19:07
  • of course, my original logger2 object was the same object as logger1, because I chose the same name! Thank you, I was hoping it was something simple. – spacediver Oct 20 '20 at 19:10

1 Answers1

0

Thanks to @Abhinav Mathur for the answer provided in the comments.

The issue was that by attempting to create logger2 with the same name as logger1, I was in effect not creating a new logger object.

spacediver
  • 109
  • 1
  • 10