Arran Duff
Arran Duff

Reputation: 1474

Duplicate logs when calling logging.basicConfig

Problem: When I call logging.basicConfig in addition to configuring my own logger, I get duplicate logs

Code to reproduce the issue

import logging
import sys

# create a logger, add a handler and a formatter
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s"))
log.addHandler(handler)

# call basicConfig
logging.basicConfig(level=logging.INFO) # logs not duplicated if this line is removed

# create a log message
log.info("hello world")

# verify the number of handlers on the logger
print(f" num_handlers = {len(log.handlers)}")

#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#INFO:__main__:hello world
#INFO:__main__:hello world
#num_handlers = 1

Upvotes: 0

Views: 607

Answers (1)

blues
blues

Reputation: 5195

Python loggers exist in a hierarchy. There is a root logger (accessible with root = logging.getLogger()) which is always at the root/top of the hierarchy, and which is configured when basicConfig is being called. Every other logger propagates their logs up the hierarchy, so every log will eventually reach the root logger (more exactly: the root loggers handlers).

One possible solution is to stop your logger propagating:

log = logging.getLogger(__name__)
log.propagate = False

Upvotes: 1

Related Questions