Alesi Rowland
Alesi Rowland

Reputation: 441

logger logging without a handler

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.

Upvotes: 3

Views: 1809

Answers (1)

dragon2fly
dragon2fly

Reputation: 2439

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.

Upvotes: 5

Related Questions