Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Set a named logger’s threshold with setLevel()

Set a named logger to `logging.INFO` to drop `DEBUG` while allowing `INFO` and higher levels past the logger’s threshold. The handler still controls what reaches its output.

Version: Python 3.12

Syntax

logger = logging.getLogger(name)
logger.setLevel(level)  # e.g. logging.INFO or "INFO"

The instance method logging.Logger.setLevel sets the threshold of the logger you call it on. In Python 3.12, logging.getLogger("root") returns the root logger, so calling setLevel() on it sets the root logger’s threshold. Looking up the same name again returns the same object. Pass an integer constant such as logging.INFO or a level name such as "INFO". At that threshold, DEBUG is dropped; INFO, WARNING, ERROR, and CRITICAL pass the logger’s level check.

A new non-root logger starts at logging.NOTSET. This means it takes its effective threshold from the nearest ancestor whose level is not NOTSET. If all its ancestors, including the root logger, are also at NOTSET, its effective level is NOTSET. The root logger defaults to WARNING. Use logger.getEffectiveLevel() to inspect the effective threshold.

setLevel() does not add a handler or choose a destination. Each handler has its own threshold (Handler.setLevel) and can have filters, so a record that passes the logger’s check might still produce no output. During propagation, records go directly to ancestor handlers without rechecking the ancestor loggers’ levels or filters. Set logger.propagate = False to stop forwarding to ancestors.

Examples

import logging
import sys

logger = logging.getLogger("cktis.checkout")
logger.setLevel(logging.INFO)
logger.propagate = False

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)

logger.debug("Checking cart")
logger.info("Order accepted")
logger.warning("Receipt delayed")

Result

INFO: Order accepted
WARNING: Receipt delayed

The handler writes to `sys.stdout`, and its default `NOTSET` level does not reject records by severity. With propagation off, in a fresh process the logger drops `DEBUG`, and `INFO` and `WARNING` each appear once.

Related lessons

  • Python · Lesson 27 · Advanced · Version: 5
  • Python · Lesson 24 · Intermediate · Version: 3

Sources