0

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?

1
  • What is _LOGGER_NAME? Commented Aug 10, 2018 at 20:35

2 Answers 2

1

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.

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.

To have it do what you want, just call init_logger() in your second file:

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You didn't call init_logger() (before calling logger.info()) so the level of your non-default _LOGGER_NAME was not set.

Also note the typo: if name == '__main__': -> if __name__ == '__main__':

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.