3

Why is it that a script which has:

import logging

logger = logging.getLogger(__name__)
logger.warning("warning message")

will emit a message to stderr despite not having a handler? Subsequently calling:

logger.setLevel(logging.DEBUG)
logger.info("info_message")

doesn't log anything unless I first attach a handler. Checked the hierarchy and this loggers parent is the root which also doesn't have a handler.

1 Answer 1

5

Because there is a logging.lastResort handler

A handler of last resort is available through this attribute. This is a StreamHandler writing to sys.stderr with a level of WARNING, and is used to handle logging events in the absence of any logging configuration. The end result is to just print the message to sys.stderr. This replaces the earlier error message saying that “no handlers could be found for logger XYZ”. If you need the earlier behaviour for some reason, lastResort can be set to None.

New in version 3.2.

You didn't set the logging level for your logger, so it is NOTSET. It accepts any log record and propagates to the root logger.

The root logger level has a default level of WARNING so only log records with this level is processed.

Since there is no handler in root, lastResort handler is used.

1
  • 1
    Also it is critical to point out that the level of lastResort handler is by default WARNING. So even if you change the logger level to DEBUG, the message won't pass the lastResort handler.
    – jdhao
    Commented May 27, 2022 at 9:08

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.