CKTIS / Python
Attach a logging handler and stop propagation
Use `addHandler()` to attach a handler to a specific logger, and set `propagate = False` to keep its records from reaching handlers on ancestor loggers, including the root logger.
Version: Python 3.12
Syntax
logger.addHandler(hdlr)
logger.propagate = Falselogging.Logger.addHandler attaches an existing handler object to a specific logger. Get the logger with logging.getLogger(name) and pass an object such as a logging.StreamHandler instance to logger.addHandler(hdlr), not the class itself. The handler determines the destination; its formatter determines how the text looks. To detach the handler, call logger.removeHandler(hdlr) rather than editing logger.handlers directly.
The originating logger first applies its effective level and its own filters. An accepted record is offered to local handlers and, with the default propagate = True, to handlers on successive ancestor loggers unless propagation stops along the way. The ancestor loggers' levels and filters are not checked during forwarding, but each handler still applies its own threshold and filters.
Setting logger.propagate = False stops forwarding above that logger after its local handlers have had a chance to process the record. It neither disables the logger nor reconfigures the root logger; no handler farther up that branch receives the record. If local and ancestor handlers write to the same destination, propagation can produce what looks like duplicate output. If a shared destination is enough, attach the handler only to the appropriate ancestor and leave propagation enabled.
Examples
import logging
import sys
logging.basicConfig(
level=logging.WARNING,
stream=sys.stdout,
format="root: %(message)s",
)
logger = logging.getLogger("cktis.demo")
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("local: %(message)s"))
logger.addHandler(handler)
logger.info("first")
logger.propagate = False
logger.info("second")
Result
local: first root: first local: second
Run the script in a fresh Python 3.12 process. `first` appears twice, once with `local:` and once with `root:`. The root logger's `WARNING` level does not block the forwarded `INFO` record because it goes directly to the root handler. After propagation is disabled, `second` appears only with `local:`.
Related lessons
- Python · Lesson 24 · Intermediate · Version: 3