Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Attach and detach logging handlers with addHandler

Inspect the handlers attached directly to a logger, attach a configured handler with `addHandler()`, and empty the list through `removeHandler()` rather than editing it directly.

Version: Python 3.12

Syntax

logger.handlers
logger.addHandler(handler)
logger.removeHandler(handler)

# Detach all directly attached handlers during controlled reconfiguration:
for handler in tuple(logger.handlers):
    logger.removeHandler(handler)

In Python 3.12, logger.handlers is the list of handlers attached directly to that logger, not its ancestors' handlers. You can inspect it with an expression such as len(logger.handlers), but treat it as read-only. logger.addHandler(handler) attaches an existing logging.Handler instance, such as a logging.StreamHandler; the call itself does not log a message.

Do not use logger.handlers.clear(): it empties the list but bypasses the locks used by addHandler() and removeHandler(). To detach all direct handlers during controlled reconfiguration, iterate over tuple(logger.handlers) and call logger.removeHandler(handler) for each item. The snapshot avoids iterating over a list you are changing, but does not make the whole operation atomic. Detaching does not close a handler; call handler.close() separately if you own it and it is no longer in use.

With propagate enabled, a record can also reach ancestor handlers, which can produce duplicate output. logger.propagate = False stops forwarding to ancestors. An empty direct handler list does not guarantee silence: if no handler is found along the propagation path, logging.lastResort can handle the record.

Examples

import logging
import sys

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

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

print(len(logger.handlers))
try:
    logger.addHandler(console)
    print(len(logger.handlers))
    logger.info("ready")
finally:
    for attached in tuple(logger.handlers):
        logger.removeHandler(attached)
    console.close()

print(len(logger.handlers))

Result

0
1
INFO: ready
0

Run the script in a fresh Python 3.12 process. The counts `0`, `1`, and `0` show the number of direct handlers before attachment, after attachment, and after removal. The handler writes `INFO: ready` to standard output.

Related lessons

  • Python · Lesson 27 · Advanced · Version: 5

Sources