2

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.

Alesi Rowland
  • 379
  • 2
  • 16

1 Answers1

4

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.

dragon2fly
  • 2,309
  • 19
  • 23
  • 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 May 27 '22 at 09:08