python log level not setting
Clash Royale CLAN TAG#URR8PPP
python log level not setting
In file 1:
def get_logger():
return logging.getLogger(_LOGGER_NAME)
def init_logger():
message_format = logging.Formatter(fmt='%(asctime)s %(name)s >>> %(message)s',
datefmt='%Y-%m-%d %H-%M-%S')
console_info_handler = logging.StreamHandler(sys.stdout)
console_info_handler.setLevel(logging.INFO)
console_info_handler.setFormatter(fmt=message_format)
logger = logging.getLogger(_LOGGER_NAME)
logger.addHandler(console_info_handler)
logger.setLevel(logging.INFO)
return logger
In file 2:
if name == '__main__':
logger = get_logger()
logger.info(logger.level)
Does not print anything (imports are in place of course). And if I go:
if __name__ == '__main__':
logger = get_logger()
logger.critical(logger.level)
The output is 0, instead of the expected 20. So it looks like the logger level isn't set at the level that I thought it was. Moreover, the level is lower than I thought it was, yet it still doesn't log on logger.info. What am I doing wrong here? Oh and bonus question (since I stole the above code and don't know any of python's logging intricacies), how does resolution of a log message happen if the logger's level and the handler's level clash?
_LOGGER_NAME
2 Answers
2
File 2 only calls get_logger()
and not init_logger()
. Thus, setLevel is never called on the logger, so its given the default value of NOTSET
.
get_logger()
init_logger()
NOTSET
Take a look at: https://docs.python.org/3/library/logging.html#logging.Logger.setLevel
By default, the root logger is created with level WARNING
. This is why logger.info(logger.level)
does nothing as INFO
is below WARNING
. logger.critical(logger.level)
, on the other hand, outputs 0 as this is the numeric value of NOTSET
.
WARNING
logger.info(logger.level)
INFO
WARNING
logger.critical(logger.level)
NOTSET
To have it do what you want, just call init_logger()
in your second file:
init_logger()
if __name__ == '__main__':
logger = init_logger()
logger.info(logger.level)
To answer your bonus question: the handler gets whatever messages get through the logger.
If the level of the logger is DEBUG
, and the level of the handler is INFO
, the handler will receive all messages from the DEBUG
Level and up, but will only output messages on the INFO
level and up.
DEBUG
INFO
DEBUG
INFO
You didn't call init_logger()
(before calling logger.info()
) so the level of your non-default _LOGGER_NAME
was not set.
init_logger()
logger.info()
_LOGGER_NAME
Also note the typo: if name == '__main__':
-> if __name__ == '__main__':
if name == '__main__':
if __name__ == '__main__':
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What is
_LOGGER_NAME
?– user2357112
Aug 10 at 20:35