Sub topic 7
The logger hierarchy and propagation
This chapter assumes you can create loggers with logging.getLogger, know the five standard levels, and have attached a handler to a logger. It covers how Python connects loggers into a tree and how a record travels through that tree. Most surprises in logging (duplicate lines, missing messages, a level that seems ignored) come from this mechanism.
Names define the tree
Logger names are dot-separated. The dots define parent and child relationships:
"myapp"is the parent of"myapp.db"."myapp.db"is the parent of"myapp.db.pool".- The root logger, returned by
logging.getLogger()with no argument, is the ancestor of every logger.
Calling getLogger with the same name always returns the same object. A logger exists as soon as you ask for it, and you never declare the parent first. If you create "a.b.c" without ever creating "a" or "a.b", Python inserts placeholder entries for the missing ancestors. Placeholders have no handlers and no level, and records pass through them.
This is why logging.getLogger(__name__) is the standard idiom. A module named myapp.db.pool automatically gets a logger at the matching spot in the tree, so the package structure becomes the logger hierarchy.
Effective level
Each logger has a level, which may be unset (NOTSET, the default for every logger except root). The root logger starts at WARNING. A logger with no level of its own uses the level of its nearest ancestor that has one. This is its effective level, and you can read it with getEffectiveLevel().
import logging
logging.basicConfig(level=logging.INFO)
parent = logging.getLogger("myapp")
child = logging.getLogger("myapp.db")
parent.setLevel(logging.WARNING)
print(child.getEffectiveLevel() == logging.WARNING)
child.info("Dropped: the child inherits WARNING from its parent")
child.warning("Shown: propagates to the root logger's handler")The script prints True, then only the warning. Calling child.setLevel(logging.NOTSET) removes a level you set earlier and restores inheritance.
The path of a record
When you call logger.info(...), logging follows these steps:
- It checks the logger's effective level. If
INFOis below it, the call stops here and no record is created.logger.isEnabledFor(level)runs this same check. - It builds a
LogRecordand runs the logger's filters. A filter can reject the record. - It passes the record to every handler attached to this logger. Each handler checks its own level and filters, then emits.
- If the logger's
propagateattribute isTrue(the default), the record moves to the parent logger's handlers, and then to the grandparent's, up to the root.
Step 4 is the part people misremember. The record is handed directly to the ancestors' handlers. The ancestors' logger levels and logger filters are not consulted. Only the level of the originating logger counts, plus each handler's own level.
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(name)s %(levelname)s %(message)s",
)
logging.getLogger("myapp").setLevel(logging.WARNING)
logging.getLogger("myapp.db").setLevel(logging.DEBUG)
logging.getLogger("myapp.db").debug("shown")
logging.getLogger("myapp").debug("dropped")Only myapp.db DEBUG shown appears. The child's own DEBUG level lets the record be created. The parent's WARNING does not stop it, because propagation skips the parent's level check. The root handler accepts everything, so the record is printed.
Level checks in summary
| Check | Where it applies | Uses |
|---|---|---|
| Logger level | Only the logger on which you call `.info()` etc. | Effective level (own or inherited) |
| Logger filters | Only the originating logger | Filters attached to that logger |
| Handler level | Every handler reached, on any ancestor | The handler's own level |
| Handler filters | Every handler reached | Filters attached to that handler |
When you need to silence a noisy subtree, set the level on the topmost logger of that subtree, and make sure no descendant overrides it. When you need to silence one destination, set the level on the handler.
Duplicate output
Propagation causes the most common logging bug: every message appears twice. It happens when a handler exists on both a logger and one of its ancestors.
import logging
logging.basicConfig(level=logging.INFO, format="root: %(name)s %(message)s")
app = logging.getLogger("myapp")
app.addHandler(logging.StreamHandler())
app.info("hello")The output has two lines on stderr:
hello
root: myapp helloThe first comes from the handler on myapp. The record then propagates to the root logger, where basicConfig installed a second handler. Handlers on the originating logger run first, then ancestors in order.
You have two fixes:
- Attach handlers only at one point, usually the root. Child loggers then need no handlers. This is the recommended approach for applications.
- Set
propagate = Falseon a logger that has its own complete handler setup.
import logging
logging.basicConfig(level=logging.INFO, format="root: %(name)s %(message)s")
app = logging.getLogger("myapp")
app.addHandler(logging.StreamHandler())
app.propagate = False
app.info("hello")Now only hello is printed. Handlers on the root logger never see records from myapp or its descendants, because propagate = False stops the walk after myapp's own handlers.
A related cause of duplicates is code that adds a handler every time a function runs, for example inside a request handler or a function called in a loop. Each call adds another handler to the same logger object. Configure handlers once at startup.
When there are no handlers
If the walk up the tree finds no handlers at all, Python uses logging.lastResort. This is a stderr handler at level WARNING that prints only the message, with no timestamp or logger name. This is why a bare logging.warning("x") in a script prints something even though you configured nothing, while logging.info("x") prints nothing.
Inspecting the tree
When behavior is unclear, ask the objects directly:
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("myapp.db.pool")
logger = log
while logger is not None:
print(
f"{logger.name!r:18} level={logging.getLevelName(logger.level):8} "
f"handlers={len(logger.handlers)} propagate={logger.propagate}"
)
logger = logger.parentThis prints one line for myapp.db.pool and one for root, because the placeholder entries are skipped when the parent is resolved. The parent attribute gives the nearest real ancestor. Note that logger.level is the logger's own setting (NOTSET is shown as NOTSET), while getEffectiveLevel() is the inherited result.
Related settings and edge cases
disabled: a logger withdisabled = Truedrops records.fileConfiganddictConfigcan set this on existing loggers that your configuration does not mention. Setdisable_existing_loggerstoFalseindictConfigto avoid it.- Level changes take effect immediately. Python caches level checks internally, but
setLevelclears the cache, so you do not need to restart anything. - Names are case-sensitive.
"MyApp"and"myapp"are unrelated loggers. - Avoid trailing dots or empty segments in names. They create odd hierarchy entries and nothing useful.
- Loggers are never garbage collected in normal use. Do not create a logger per object or per request by using unique names, or the registry grows without bound.
Exercise
A module logs with logging.getLogger("shop.cart"). The root logger has a handler with level DEBUG and the root level is DEBUG. shop has its level set to ERROR, and shop.cart has no level set. The code calls logger.warning("low stock") on shop.cart. Is the message printed? What changes if you also call logging.getLogger("shop.cart").setLevel(logging.DEBUG)?
Show answer
It is not printed. shop.cart has no level, so its effective level is ERROR (inherited from shop), and WARNING is below ERROR. The record is dropped at step 1 and never reaches any handler. After shop.cart is given the level DEBUG, the record is created and propagates to the root handler, which accepts it, so the message is printed. The ERROR level on shop is not consulted during propagation.