Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Logger handlers: inspect, detach, and attach

In Python 3.12, `logger.handlers` shows only the handlers attached directly to a logger. Read the list to inspect it; use `addHandler()` and `removeHandler()` to change it.

Version: Python 3.12

Syntax

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

# Detach every handler in the snapshot of this logger's direct attachments.
for handler in list(logger.handlers):
    logger.removeHandler(handler)

logging.Logger.handlers is an instance attribute: it holds the list of handlers attached directly to that logger. It does not include handlers on ancestor loggers, and it is not the logging.handlers module. len(logger.handlers) counts direct attachments only.

Treat the list as read-only. Call logger.addHandler(handler) to attach a handler and logger.removeHandler(handler) to detach one. Do not use logger.handlers.clear(), append(), or assignment: those bypass the locks used by the methods. To empty the list, iterate over a copy, list(logger.handlers), and call removeHandler() for each item. The copy avoids changing the list you are iterating over, but the whole operation is not atomic.

Detaching does not close a handler. Call handler.close() separately for a handler you own when it is no longer needed anywhere. Do not close a handler just because you detached it from one logger: it may still be shared.

An empty list does not mean silence. logger.hasHandlers() also searches ancestors reachable through propagation; it tests for the presence of a handler, not whether a particular record will be emitted. logger.propagate = False stops forwarding to ancestors. If no handler is found on the resulting path, logging.lastResort can still apply; by default it writes records at WARNING or above to standard error.

Examples

import logging
import sys

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

old_handler = logging.NullHandler()
logger.addHandler(old_handler)
print('before:', len(logger.handlers))

for handler in list(logger.handlers):
    logger.removeHandler(handler)
old_handler.close()
print('cleared:', len(logger.handlers))

new_handler = logging.StreamHandler(sys.stdout)
new_handler.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(new_handler)
try:
    print('attached:', len(logger.handlers))
    logger.info('ready')
finally:
    logger.removeHandler(new_handler)
    new_handler.close()

Result

before: 1
cleared: 0
attached: 1
ready

Run the example in a fresh process. The counts show one direct handler, an empty list, and one replacement handler. The new `StreamHandler` writes `ready`, and the `finally` block detaches and closes it.

Related lessons

  • Python · Lesson 27 · Advanced · Version: 5

Sources