A few things to clarify:
- Default log level for root logger is
WARNING
Root logger is not initialized if you do nothing, that is, without any handlers or formatter set up:
>>> import logging
>>> logging.root.handlers
[]
Okay, but you found out the problem: when logging level set to DEBUG
, the root logger is not working as expected. Debug messages are ignored. With the same not configured root logger, warning messages output normally. Why is that?
Keep in mind we don't have any handler for root logger right now. But looking into the code, we do see:
if (found == 0):
if lastResort:
if record.levelno >= lastResort.level:
lastResort.handle(record)
elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
sys.stderr.write("No handlers could be found for logger"
" "%s"
" % self.name)
self.manager.emittedNoHandlerWarning = True
Which means, we have a lastResort
for backup if no handler is found. You can refer to the definition of lastResort
, it is initialized with logging level WARNING
. Meanwhile, debug messages don't have this backup so they are ignored when no handler is set.
For your questions:
- These two loggers are identical, since the root logger is returned when
getLogger()
receives no arguments.
- See below:
Logger.isEnabledFor(lvl)
Indicates if a message of severity lvl would
be processed by this logger. This method checks first the module-level
level set by logging.disable(lvl) and then the logger’s effective
level as determined by getEffectiveLevel().
- Calling any logging functions in
logging
module will initialize the root logger with basicConfig()
which adds a default handler, so that the subsequent calls on logger
will also work.
What you should do is, use logging.basicConfig()
to set up a default handler for root logger and messages will be output according to the logger level and message level.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…