Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Get a child logger with Logger.getChild

Look up a logger relative to its parent’s name and send its records to the parent’s handler without copying that handler onto the child.

Version: Python 3.12

Syntax

parent_logger.getChild(suffix)

logging.Logger.getChild(suffix) is an instance method available since Python 3.2. For a non-root logger, it appends a dot and the string suffix to the logger’s name, then looks up the resulting name. For the root logger, it uses the suffix directly, without the root. prefix. If app is the logger named app, app.getChild("validation") returns the same object as logging.getLogger("app.validation"). The suffix can contain dots: validation.rules names a deeper descendant.

The method does not copy handlers. When app.validation accepts a record and has propagate=True (the default), the record also reaches the handlers attached to app. Setting app.propagate = False leaves those handlers active but stops the record from continuing to the root logger.

A logger’s threshold and a handler’s threshold apply at different stages. With its level left at NOTSET, app.validation uses app’s INFO as its effective level in the example. Once the record is accepted, propagation does not reapply ancestor logger levels or filters, but each handler still applies its own threshold and filters. Attaching the same handler to both the child and the parent can print the same record twice.

Examples

import logging
import sys

app = logging.getLogger("app")
app.setLevel(logging.INFO)
app.propagate = False

handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(name)s | %(levelname)s | %(message)s"))
app.addHandler(handler)

validation = app.getChild("validation")
assert validation is logging.getLogger("app.validation")
validation.info("Input accepted")

Result

app.validation | INFO | Input accepted

Run the script in a fresh Python 3.12 process. The assertion uses `is` to check object identity. The only handler is attached to `app`, but the output says `app.validation` because that logger created the record.

Related lessons

  • Python · Lesson 24 · Intermediate · Version: 3

Sources