PREP WITH PROOF
Menu
PROGRAMMING / PRACTICAL GUIDE

Python Logging Duplicate Messages: Handlers and Propagation

Fix duplicate Python logging messages by tracing handlers, propagation, logger levels and startup configuration. Includes a tested standard-library lab.

THE QUICK ANSWER

Duplicate Python log lines often occur when one record reaches both a local handler and an ancestor handler, or setup repeatedly creates handlers. Trace the output path before changing propagation, then verify logger thresholds, handler thresholds and configuration ownership independently.

First identify whether one record or two events reached the output

Two identical lines do not necessarily mean the application executed a log statement twice. One logging record can reach several handlers, and those handlers can write to the same destination. A different problem occurs when a retry, worker or repeated callback creates two separate records with the same message. Start with a controlled request or action and include logger name, process identity and a correlation identifier in the development output.

Observe the output as close to the Python process as practical. If stderr contains one line but the log platform shows two, investigate collection routes before altering Python configuration. A container runtime, sidecar and separate agent can collect overlapping streams. Conversely, if the process already emits two lines, changing collector deduplication can conceal the local configuration defect.

A useful diagnostic is to temporarily give handlers different formatter prefixes in a development environment. If one call produces local:event and root:event, the path is visible. Keep the change narrow and remove it after diagnosis. Avoid putting private request bodies or credentials into a formatter simply to distinguish events.

Also decide what counts as duplication for the application. Sending one event to a console and a separate audit destination may be intentional. The problem is two unwanted copies in the same intended view, not the existence of more than one handler anywhere in the system.

ObservationLikely investigationEvidence to collect
One call, two handler labelsHandler placement and propagationLogger ancestry and direct handlers
Each setup call adds another lineRepeated configuration creates distinct handlersHandler identities before and after setup
One process line, two platform entriesCollector or forwarding routesRaw process output and collector configuration
Same text from different processesWorkers or repeated application workPID and request/event identity

Source: Python Logging Cookbook — application/library patterns ↗

Trace the logger hierarchy before switching propagation off

Python logger names form a hierarchy: app.worker is below app and ultimately the root logger. getLogger with the same name returns the same logger in one interpreter. Creating another variable for that name does not create an independent logging channel. That is why adding handlers in a frequently called setup function can accumulate state across calls.

With propagation enabled, an accepted record is offered to handlers on the emitting logger and then its ancestors until propagation stops. A handler on app.worker and another on root can therefore both emit one record. A common application design puts the output handlers on root or an appropriate application parent and lets module loggers propagate.

A separate design attaches a complete output policy to a particular logger and sets propagate=False there. This can be appropriate for an intentionally isolated channel. It can also remove output from an expected central destination, so verify the desired routing before applying it as a universal duplicate-message fix. Turning it off without a suitable handler can produce missing logs rather than a repaired system.

Inspect direct handlers and inherited availability separately. logger.handlers lists handlers directly attached to that logger, while hasHandlers searches the relevant ancestry. A child can have an empty direct list and still have an output route. Using hasHandlers as shorthand for “my setup already installed its own handler” confuses those two questions.

Source: Python logging — hierarchy, handlers, levels and basicConfig ↗

Logger thresholds and handler thresholds answer different questions

The emitting logger’s effective level decides whether a normal log call creates a record for handling. A non-root logger at NOTSET inherits an effective threshold from its ancestry. Once a record propagates, the ancestor logger’s level and logger filters are not applied again; the ancestor handlers still apply their own levels and filters.

This explains a surprising test case: a child explicitly set to DEBUG can send an INFO record to a root handler even when root itself is set to ERROR, if that handler allows INFO. If instead the child is NOTSET, root’s ERROR level can prevent that child’s INFO call from being accepted in the first place. The handler setting and effective logger setting solve different problems.

When reducing volume, specify where the policy belongs. A handler threshold can restrict a console while another destination retains detailed records. A logger threshold can suppress records from a particular namespace before they reach any handler. Verify both expected arrivals and expected absences; a configuration that removes duplicates by dropping every INFO message has not preserved the original behavior.

Filters require the same attention to placement. A filter attached to an ancestor logger does not automatically inspect propagated records from its descendants. Put destination-specific filtering on the handler when that is the intended policy, and test the real route rather than assuming every object in the ancestry rechecks each record.

Source: Python logging — hierarchy, handlers, levels and basicConfig ↗

Give configuration one owner and one defined startup point

Application code should decide where output goes. Library modules can obtain named loggers and emit records without repeatedly installing application output handlers. The logging cookbook discusses library configuration patterns and common pitfalls, including attaching inappropriate handlers. Keep configuration out of per-request functions and object constructors unless that lifecycle explicitly owns a distinct channel.

basicConfig is convenient at an application entry point, but it normally does nothing when root already has handlers. Calling it repeatedly is not, by itself, proof that new duplicate handlers were added. A notebook or framework may already have configured root before your code runs. Inspect the current state instead of assuming a call changed the format or level.

The force=True option replaces and closes existing root handlers. Use it only when the application actually owns that root configuration; it can disrupt framework or test-capture output. It also does not mean every handler attached to every named logger has been removed. Blindly clearing handlers across the entire process can erase intentional routes and make diagnosis harder.

For a centralized dictionary configuration, make the existing-logger policy explicit. The nonincremental dictConfig schema defaults disable_existing_loggers to True when omitted. Choosing False can preserve other named loggers, but it does not decide which inherited and local handlers should exist in the final design. Treat that choice as part of an explicit application configuration, not a blanket fix for every framework.

Source: Python logging.config — dictionary configuration schema ↗

Run the routing experiment in a fresh interpreter

The complete standard-library fixture below uses an in-memory stream. Save it as logging60_lab.py and run python -I logging60_lab.py in a new process. It deliberately refuses to start if root already has handlers, so notebook or test-runner configuration is not silently overwritten. It creates no log files and contacts no network service.

The experiment starts with one root handler, then adds a local handler and observes two labeled lines from one call. It disables propagation to keep only the local route, removes that handler, and tests ancestor levels, handler levels and an ancestor filter separately. It also verifies the distinction between direct handlers and hasHandlers, and that a no-op basicConfig leaves the existing root policy intact.

The last cases add two distinct root handlers, verify that adding the same handler object again does not add a second attachment to that logger, and apply a centralized dictionary configuration. This differentiates repeated creation of new handler objects from repeated references to the same object. The fixture then removes and closes the handlers it owns.

The exact published code passed 13 checks with Python 3.12.14 in a fresh isolated process. These are actual standard-library routing checks, not a mocked logging model. They do not test multiprocessing, concurrent reconfiguration, file rotation, asynchronous queues, a web framework or a remote collector. Adapt the startup ownership model before using any configuration change in an existing service.

# Run as a fresh process: python -I logging60_lab.py
import io
import logging
import logging.config

root = logging.getLogger()
assert not root.handlers, 'Use a fresh isolated interpreter'
logger = logging.getLogger('demo.worker')
logger.setLevel(logging.DEBUG)
logger.propagate = True
stream = io.StringIO()
checks = 0


def handler(label, level=logging.NOTSET):
    h = logging.StreamHandler(stream)
    h.setLevel(level)
    h.setFormatter(logging.Formatter(label + ':%(message)s'))
    return h


def lines():
    value = stream.getvalue().splitlines()
    stream.seek(0); stream.truncate(0)
    return value


try:
    assert logging.getLogger('demo.worker') is logger
    checks += 1
    rh = handler('root')
    root.addHandler(rh)
    logger.info('one')
    assert lines() == ['root:one']
    checks += 1
    lh = handler('local')
    logger.addHandler(lh)
    logger.info('two')
    assert lines() == ['local:two', 'root:two']
    checks += 1
    logger.propagate = False
    logger.info('three')
    assert lines() == ['local:three']
    checks += 1
    logger.removeHandler(lh); lh.close()
    logger.propagate = True
    root.setLevel(logging.ERROR)
    logger.info('ancestor-level')
    assert lines() == ['root:ancestor-level']
    checks += 1
    rh.setLevel(logging.ERROR)
    logger.info('handler-level')
    assert lines() == []
    checks += 1
    rh.setLevel(logging.NOTSET)
    logger.setLevel(logging.NOTSET)
    logger.info('inherited-level')
    assert lines() == []
    checks += 1
    logger.setLevel(logging.INFO)
    root_filter = logging.Filter('unrelated')
    root.addFilter(root_filter)
    logger.info('ancestor-filter')
    assert lines() == ['root:ancestor-filter']
    root.removeFilter(root_filter)
    checks += 1
    assert logger.handlers == [] and logger.hasHandlers()
    checks += 1
    logging.basicConfig(stream=stream, level=logging.DEBUG)
    assert root.handlers == [rh] and root.level == logging.ERROR
    checks += 1
    second = handler('second')
    root.addHandler(second)
    logger.info('distinct-handlers')
    assert lines() == ['root:distinct-handlers', 'second:distinct-handlers']
    checks += 1
    root.addHandler(second)
    assert root.handlers.count(second) == 1
    checks += 1
    logging.config.dictConfig({
        'version': 1, 'disable_existing_loggers': False,
        'handlers': {'console': {
            'class': 'logging.StreamHandler', 'stream': stream}},
        'root': {'level': 'INFO', 'handlers': ['console']}})
    logger.info('configured-once')
    assert lines() == ['configured-once']
    checks += 1
    print(f'{checks} checks passed; standard-library handlers, no files or network')
finally:
    for owner in (logger, root):
        for h in owner.handlers[:]:
            owner.removeHandler(h); h.close()

Verify the repair across startup and application work

Once the cause is known, make the smallest routing change consistent with the intended destinations. If configuration repeatedly constructs handlers, move that work to the owned startup phase or replace it with a configuration mechanism whose lifecycle is clear. A check followed by addHandler is not a general synchronization mechanism for concurrent startup. Keep setup ordered instead of adding an untested race-prone guard.

Rerun the action that exposed the problem and compare the per-destination result. Verify one accepted event reaches each intended destination once, important warning and error events still arrive, and lower-severity filtering behaves as designed. Exercise the startup path again if the application supports reinitialization, because a single clean first launch can hide accumulation on later setup calls.

Keep application retries separate from routing. If the same business operation runs twice, repair or document that lifecycle and retain identifiers that distinguish the attempts. If the duplicate begins only after forwarding, trace that downstream route. Removing a legitimate handler to hide repeated work changes the evidence without addressing the cause.

A reliable logging fix leaves an explainable path from the emitting logger to every destination. Choose handler placement and propagation together, apply levels and filters at the intended stage, and configure the process at an owned lifecycle point. The goal is predictable records that remain useful during the next failure.

KEEP THESE THREE THINGS

Your next steps

  1. One record can be emitted by several handlers; identical text can also come from separate events.
  2. Choose ancestor-only routing or an intentional isolated logger policy.
  3. Ancestor logger levels do not re-filter propagated records; handler levels still apply.
  4. Configure output at an owned startup point and verify repeated initialization.

Sources & official resources

Linked resources checked on 2026-10-30. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →