I created the following script. Could any of you explain to me why the output is like what shows below
Source
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
print('debug', logger.isEnabledFor(logging.DEBUG))
print('info', logger.isEnabledFor(logging.INFO))
print('warning', logger.isEnabledFor(logging.WARNING))
print('error', logger.isEnabledFor(logging.ERROR))
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
Output
debug True
info True
warning True
error True
warning
error
DEBUG:root:debug
INFO:root:info
WARNING:root:warning
ERROR:root:error
Specifically
what is the difference between
logger.info
andlogging.info
herehow come that
logger.isEnabledFor(logging.DEBUG)
isTrue
whilelogger.debug('debug')
does not show anythinghow come that
logger.info
has no output butlogging.info
has
A few things to clarify:
WARNING
Root logger is not initialized if you do nothing, that is, without any handlers or formatter set up:
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:
Which means, we have a
lastResort
for backup if no handler is found. You can refer to the definition oflastResort
, it is initialized with logging levelWARNING
. Meanwhile, debug messages don't have this backup so they are ignored when no handler is set.For your questions:
getLogger()
receives no arguments.logging
module will initialize the root logger withbasicConfig()
which adds a default handler, so that the subsequent calls onlogger
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.getLogger creates an instance of Logger class if argument
name
is added. Otherwise it returns root logger. So in this case the program is using the common logger as functionslogging.debug
,logging.info
,logging.warning
,logging.info