LOGGERS · LEVELS · HANDLERS · RECORDS · JSON · CONTEXT · WHAT NOT TO LOG

Logging in Python:
how a log line is made and what to put in it

Python’s logging module turns one call in your code into a line on your program’s output. On the way it decides whether the line is written, what it contains and where it goes. You set those decisions once, at startup, and a few habits decide whether the lines help you find a problem later.

A small online shop pays for an order, then asks its shipping service for a label. The service calls a parcel carrier’s API, stores the label and returns a tracking number. With customers checking where their parcels are, that is 1,000,000 requests a day (an illustrative figure). Each chapter looks at the lines one of those requests leaves in the log, starting with a service whose lines nobody can use.

Here is the path one log record takes inside the service. Most boxes won’t mean much yet; each chapter explains one of them.

MapArrows follow one record from the call at the bottom left to the line on stdout. Chips sit beside the part that owns them.

You need Python functions, modules and try/except; no study of logging is assumed. The tutorial teaches Python 3.15 and structlog 26.1.0, checked against their source and documentation on 2 December 2026; samples use only the standard library unless they say otherwise. The shop, its ids and its traffic are made up; every default, message and format comes from the libraries themselves. Tap any figure to open it full screen and zoom. Dotted terms are tappable.

Loggers: one per module, named after it

shipyard reports what it does with print(). Every line looks the same, nothing says which module wrote it, and you can’t turn the carrier module’s chatter off without editing code. A logger fixes that: a named object each module hands its events to instead of calling print. Python’s logging module creates loggers on request and links them by name. Which logger should a module use, and why does its name matter?

STEP 01 / 02

A LOGGER’S NAME PLACES IT IN A TREE

Fig 1.1Follow the accent arrows: the carrier module’s logger has two ancestors, its package and the root.

A logger is the first part of the path a log record takes inside the service: your code, the module’s logger, its parent loggers up to the root, a handler with its filters, a formatter, and stdout. Each logger has a name, and the name decides where it sits among the others.

Dots in the name make parents. shipyard.carrier is a child of shipyard, which is a child of the root, the logger at the top of every tree. Together the names form the logger tree. logging.getLogger("shipyard.carrier") returns the same object wherever it is called in the process, so every caller of one name shares one logger.

Libraries’ loggers live in the same tree. httpx logs on one logger named httpx; its transport, httpcore, uses one per module, such as httpcore.connection. A setting on a parent covers its children, so one line of configuration can make the whole shipyard package more detailed, or quiet httpx.

STEP 02 / 02

ONE LOGGER PER MODULE, NAMED AFTER THE MODULE

Fig 1.2The accent row is the module this tutorial follows; its logger’s name is its import path.

log = logging.getLogger(__name__) at the top of every module gives each module its own logger. Python sets __name__ to the module’s import path when it imports the file, so the code in shipyard/carrier.py logs on shipyard.carrier and every line says which module wrote it. The logging howto calls this “a good convention to use when naming loggers”.

Never call logging.info() itself. The module-level functions log on the root logger, so every line is named root. And when the root has no handler yet, they call basicConfig() first, which adds a stderr handler with the format %(levelname)s:%(name)s:%(message)s. A later basicConfig() in your main() then does nothing at all, because the root already has a handler.

Libraries choose their own names. httpx calls logging.getLogger("httpx") in its client module, so all of its lines share one logger, and that name is the one you configure.

SHIPYARD/CARRIER.PY: ONE LOGGER FOR THE MODULE
# shipyard/carrier.py
import logging

import httpx

log = logging.getLogger(__name__)  # "shipyard.carrier"


def create_label(order):
    log.info("label requested")
    response = httpx.post(LABELS_URL, json=order.label_request(), headers=AUTH)
    log.info("label created")
    return response.json()

COMMON QUESTIONS

Can two modules share a logger?
They can, by asking for the same name. But then the lines of one of them carry the wrong module’s name, and you can’t set their levels apart. One logger per module costs nothing.
Should a class have its own logger?
Rarely. A module logger plus the class name in a field (chapter 05) is enough. For a class with very noisy output, getLogger(f"{__name__}.{type(self).__name__}") gives it a child logger whose level you can set on its own.

WHAT YOU NOW KNOW

  • A module gets its logger with logging.getLogger(__name__), so the logger is named after the module’s import path.
  • The dots make a tree: shipyard.carrier sits under shipyard, under the root, beside library loggers such as httpx.
  • A setting on a parent covers its children, so one line of configuration can quiet a whole package or a library.
DEEP DIVE: logging from a library, finding the loggers a process has, warn and warning

Logging from a library

A library you publish creates its loggers the same way, with getLogger(__name__), and configures nothing else. The howto is direct: “It is strongly advised that you do not add any handlers other than NullHandler to your library’s loggers.” Configuring output is the application’s job.

A NullHandler on the package’s top logger has one more effect. Python’s fallback, which prints warnings to stderr when a record finds no handler anywhere, no longer runs for the library’s records. Its warnings then appear only once the application configures logging, which is the intent.

A LIBRARY’S __INIT__.PY: A NULLHANDLER ONLY
# parcelpost_client/__init__.py: a library you publish
import logging

# Only this: the application decides levels, handlers and formats.
logging.getLogger(__name__).addHandler(logging.NullHandler())

Finding the loggers a process has

logging.root.manager.loggerDict maps every logger name created so far to its logger, or to a placeholder for a parent nobody has asked for yet. Logger.getChildren(), new in Python 3.12, returns a logger’s direct children: logging.getLogger("httpcore").getChildren() lists httpcore.connection and its siblings once they exist. Both help when a library’s lines appear and you don’t know which name to configure.

warn and warning

logger.warn still exists in Python 3.15.2. It emits a DeprecationWarning (“The warn method is deprecated, use warning instead”) and then calls warning. Write log.warning.

Levels: which lines get written

Every module now has a logger, and the carrier module logs every request it builds, every label it gets back and every retry. In production that is too much; while you chase a carrier problem it is exactly right. A level on each call, and a threshold on loggers and handlers, lets you choose without editing code. Which lines get written, and how do you pick a line’s level?

STEP 01 / 03

A RECORD PASSES TWO LEVEL CHECKS

Fig 2.1Follow each call: DEBUG stops at the logger, INFO at the handler, and only WARNING reaches stdout.

A level is a number on every call, from DEBUG 10 to CRITICAL 50, and a threshold at two points of the record’s path: the module logger, right after your code, and the handler near the end, just before the formatter and stdout. A record below either threshold stops there, so “INFO and above” means 20 or more.

First the logger compares the call with its effective level: its own level, or the first one set on an ancestor, up to the root, whose default is WARNING. Below it, the call returns before a record even exists. Then each handler compares the record with its own level. The figure sets the handler to WARNING, unlike the service’s INFO, so that each check drops one call.

With nothing configured, a record finds no handler at all, and Python falls back to the last-resort handler, which prints WARNING and above to stderr as the bare message. An INFO line is dropped either way: by the root’s default WARNING, or, if you set the logger to INFO and attach no handler, by the fallback’s level.

STEP 02 / 03

PICK THE LEVEL BY WHAT SOMEONE MUST DO

Fig 2.2The accent rows mark the line people get wrong: a retry that worked is not an error.

The logging howto gives each level a meaning. DEBUG: “Detailed information, typically of interest only when diagnosing problems.” INFO: “Confirmation that things are working as expected.” WARNING: something unexpected happened, but the software still works. ERROR: “Due to a more serious problem, the software has not been able to perform some function.” CRITICAL: the program may not be able to go on.

In the carrier module, carrier request built is DEBUG, label created is INFO, carrier slow, retrying is WARNING, label request failed is ERROR and database unreachable, shutting down is CRITICAL. Ask who must act on the line. Nobody acts on INFO. Someone looks at a WARNING that keeps happening. An ERROR means a request failed, and whoever is on call should know.

The line people get wrong is the one between WARNING and ERROR. A carrier timeout that a retry fixed is a WARNING at most, because the request still succeeded.

CARRIER.PY: ONE CALL PER LEVEL
log.debug("carrier request built")  # 10: only while diagnosing
log.info("label created")  # 20: normal, expected
log.warning("carrier slow, retrying")  # 30: unexpected, still working
log.error("label request failed")  # 40: this request failed
log.critical("database unreachable, shutting down")  # 50: the service stops
STEP 03 / 03

DEBUG LINES OUTNUMBER EVERYTHING ELSE

Fig 2.3The accent bar is the production setting; the long bar is what DEBUG costs every day.

Take illustrative traffic: 1,000,000 requests a day, 18 DEBUG lines and 3 INFO lines per request, 340 bytes a line. At threshold DEBUG the service writes about 7.15 GB a day, at INFO about 1.03 GB, and at WARNING about 7.8 MB. DEBUG writes about 7 times as much as INFO, and the log platform stores and bills every byte.

Keep production at INFO. To investigate a carrier problem, raise only shipyard.carrier to DEBUG, for as long as you need, through configuration rather than a code change. The settings below read each level from an environment variable, so a restart with LOG_LEVEL_CARRIER=DEBUG is enough. Keep httpx at WARNING too, or it writes one INFO line for every request it sends.

SETTINGS.PY: LEVELS FROM THE ENVIRONMENT, PER LOGGER
# shipyard/settings.py
import os

LEVEL = os.environ.get("LOG_LEVEL", "INFO")
CARRIER_LEVEL = os.environ.get("LOG_LEVEL_CARRIER", LEVEL)

LOGGERS = {
    "shipyard.carrier": {"level": CARRIER_LEVEL},  # DEBUG for an hour, then back
    "httpx": {"level": "WARNING"},  # otherwise one INFO line per request
}
ROOT = {"level": LEVEL, "handlers": ["stdout"]}

COMMON QUESTIONS

Should I add my own level, such as TRACE?
Avoid it. Libraries and log tools know the five standard levels. Use DEBUG on a more specific logger name instead, which you can switch on by itself.
Does a disabled DEBUG call cost anything?
Very little: the logger looks up a cached answer for that level and returns. Building the call’s arguments still costs, which chapter 04 deals with.

WHAT YOU NOW KNOW

  • A record is written only if its level clears the logger’s effective level and then each handler’s level.
  • The root starts at WARNING, so INFO lines vanish until you configure logging.
  • Choose the level by what someone must do: ERROR when an operation failed, WARNING when it recovered, INFO for normal events.
DEEP DIVE: expensive debug output, turning everything off, the last-resort handler

Expensive debug output

When building the argument itself costs, such as rendering a large structure, check first: if log.isEnabledFor(logging.DEBUG): log.debug("order %s", render(order)). Each logger caches the answer per level, and setLevel or logging.disable clears every cache, so the check stays cheap and follows configuration changes.

Turning everything off

logging.disable(logging.INFO) drops INFO and everything below it on every logger at once, whatever their levels. It is useful in tests and benchmarks. logging.disable(logging.NOTSET) undoes it.

The last-resort handler

logging.lastResort writes WARNING and above to whatever sys.stderr is at that moment, as the bare message with no level or logger name. It runs only when a record finds no handler at all on its way to the root. Any handler on the path turns it off, even a NullHandler or a handler whose level drops the record.

Set logging.lastResort = None and Python prints No handlers could be found for logger "shipyard.carrier" once instead, then stays silent.

Handlers: where the lines go, set once at startup

Records now pass or stop by level, but a logger only decides; it doesn’t write. Something must turn a record into bytes on a stream or in a file, and something must set that up once for the whole process, including the libraries. Right now shipyard has neither, so its INFO lines go nowhere. Where do log lines go, and where should that be decided?

STEP 01 / 02

A RECORD CLIMBS TO EVERY ANCESTOR’S HANDLERS

Fig 3.1Follow the record up: both handlers write it, and the ERROR level on shipyard is never checked.

A handler writes records to one destination, such as stdout or a file, and it is attached to a logger. On the record’s path it comes after the logger tree: shipyard attaches one handler, to the root logger, and that handler passes each record to a formatter and then to stdout.

After its own handlers, a logger passes the record to its parent’s handlers, then the grandparent’s, up to the root. This is propagation. The docs are exact: “neither the level nor filters of the ancestor loggers in question are considered.” Only each handler’s own level and filters apply, so the ERROR level set on shipyard never stops the carrier’s INFO record.

So a handler on both shipyard and the root writes every shipyard line twice. Attach handlers to the root only. propagate = False on a logger stops the climb after that logger’s own handlers; keep it for the rare logger whose lines must go somewhere else instead.

STDOUT: ONE RECORD, WRITTEN TWICE
2026-12-02 14:03:07,512 INFO shipyard.carrier: label created
2026-12-02 14:03:07,512 INFO shipyard.carrier: label created
STEP 02 / 02

CONFIGURE ONCE, AT STARTUP, WITH DICTCONFIG

Fig 3.2The left panel is the default: loggers the configuration doesn’t name write nothing after it runs.

shipyard/main.py calls configure_logging() before anything else runs. It hands logging.config.dictConfig one dictionary: a formatter, one StreamHandler writing to ext://sys.stdout, and levels for the root, shipyard.carrier and httpx. Every other module only calls getLogger. The Twelve-Factor App states the rule for services: “each running process writes its event stream, unbuffered, to stdout,” and the platform collects it.

Set "disable_existing_loggers": False. Module loggers are created at import, before main() runs, and with the default True, dictConfig disables every existing logger unless the configuration names it or one of its ancestors. In the figure that silences shipyard.api and shipyard.store; shipyard.carrier and httpx survive only because the loggers section names them.

MAIN.PY: ONE CONFIGURATION, AT STARTUP
# shipyard/main.py
import logging.config

from shipyard.settings import LOGGERS, ROOT


def configure_logging():
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,  # keep loggers made at import
        "formatters": {
            "text": {"format": "%(asctime)s %(levelname)s %(name)s: %(message)s"},
        },
        "handlers": {
            "stdout": {
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "formatter": "text",
            },
        },
        "loggers": LOGGERS,
        "root": ROOT,
    })


def main():
    configure_logging()  # first, before anything logs
    serve()

COMMON QUESTIONS

stdout or stderr?
In a container, either is collected. StreamHandler() defaults to stderr; shipyard sends its event stream to stdout and leaves stderr for Python’s own crash tracebacks.
Should the service write its own log files?
Not in a container: the platform stores and rotates what it collects. On a plain server, write a file and let logrotate rotate it (deep dive).

WHAT YOU NOW KNOW

  • A record climbs from its logger to the root, and every handler on the way writes it, whatever the ancestors’ levels.
  • Attach the handler to the root once; a second handler lower down duplicates lines.
  • Configure in main() with dictConfig and "disable_existing_loggers": False; modules only call getLogger.
DEEP DIVE: handlers that block, files and several processes, lines that arrive late

Handlers that block

Every emit runs in the calling thread, under the handler’s lock, so a handler that sends lines over the network slows the request that logged. A QueueHandler only puts the record on a queue; a QueueListener thread takes it off and runs the real handlers.

Since Python 3.12, dictConfig builds that listener for you and stores it on handler.listener, but never starts it, and the docs don’t say you must. Start it yourself, as below. Since 3.14 the listener also works as a context manager, and starting it twice raises RuntimeError.

QueueHandler.prepare() formats a copy of the record first, then sets args, exc_info, exc_text and stack_info to None. A JSON formatter on the listener’s side would get the traceback only as text inside the message. So put the JSON formatter on the QueueHandler, as the sample does, or override prepare.

A QUEUE BETWEEN THE REQUEST AND THE STREAM
import atexit
import logging

HANDLERS = {
    "queue": {
        "class": "logging.handlers.QueueHandler",
        "handlers": ["stdout"],  # dictConfig builds a QueueListener over these
        "formatter": "json",  # format here: the queue drops exc_info
    },
    "stdout": {
        "class": "logging.StreamHandler",
        "stream": "ext://sys.stdout",
        "formatter": "plain",  # {"format": "%(message)s"}: already JSON
    },
}
ROOT = {"level": "INFO", "handlers": ["queue"]}


def start_log_thread():
    listener = logging.getHandlerByName("queue").listener
    listener.start()  # dictConfig never starts it
    atexit.register(listener.stop)  # write what is still queued on exit

Files and several processes

The logging cookbook says plainly that logging to a single file from multiple processes “is not supported”. With several worker processes, such as Gunicorn’s, write to stdout, or send every record to one process through a queue. On a plain server where logrotate moves the file, use WatchedFileHandler, which reopens the file when it changes.

Lines that arrive late

StreamHandler flushes its stream after every record, so log lines leave the process as they are written. print() output does not: when stdout isn’t a terminal, as in a container, sys.stdout is block-buffered. Its lines wait until the buffer fills or a log line flushes the stream, and the last ones are lost if the process is killed.

Set PYTHONUNBUFFERED=1 in the container image, or run python -u, so every write leaves at once. Since Python 3.9, stderr is line-buffered either way.

The call: what one log line carries

Lines now reach stdout, but each call passes a fixed message such as "label created", which doesn’t say which shipment. The quick fix is an f-string: log.info(f"label created {shipment_id} {carrier} {ms} ms"). It works, yet the log tool now sees a different message for every shipment, the string is built even when INFO is off, and when a label request fails, its error line has no traceback. What does one log call create, and what should you pass it?

STEP 01 / 03

A LOG CALL BUILDS A RECORD, NOT A STRING

Fig 4.1The accent fields are what you passed; the logger fills in the rest.

A LogRecord is the object one log call creates, and it is what travels the rest of the path: from your code into the module logger, up through its parent to the root, through the handler and its filters to the formatter, and out to stdout. Every part after the logger reads the record, never your call.

The figure shows the record for log.info("label created %s %s %d ms", shipment_id, carrier, ms), the call the next step argues for. msg holds the template and args the three values, as you passed them. The logger adds name, the level, the file, line and function that called it, created as a Unix time, and the process, thread and asyncio task (taskName, new in Python 3.12).

Nothing has merged msg and args yet. A formatter calls record.getMessage(), which runs msg % args, and only when a handler writes the line. Because the values stay separate attributes until then, a filter can add a field and a JSON formatter can write each value under its own key.

STEP 02 / 03

PASS VALUES AS ARGUMENTS, NOT AN F-STRING

Fig 4.2Compare the bottom rows: three messages on the left, one template on the right.

log.info("label created %s %s %d ms", shipment_id, carrier, ms) passes a fixed template and the values separately. Every label line then carries the same msg, so a log tool can group them as one event and count them. This is lazy formatting: the values are merged into the text only if a handler writes the line.

An f-string is built before log.info runs, on every call, even when the level check then drops the record. Each line becomes a different message, so a day of labels looks like as many different events. The arguments themselves are still evaluated, so keep an expensive call out of them, or guard it with log.isEnabledFor(logging.DEBUG).

A wrong number of arguments doesn’t crash the request. The handler catches the error, prints --- Logging error --- and a traceback to stderr, and the program goes on. Chapter 05 goes one step further and moves the values into named fields.

AN F-STRING AGAINST ARGUMENTS
# Built before the call, written or not; a different message every time.
log.info(f"label created {shipment_id} {carrier} {ms} ms")

# One template for every shipment; merged only if the line is written.
log.info("label created %s %s %d ms", shipment_id, carrier, ms)
STEP 03 / 03

LOG AN EXCEPTION ONCE, WITH ITS TRACEBACK

Fig 4.3The accent entry is one failure, logged once, with the traceback that explains it.

Inside the except block that handles an error, log.exception("label request failed") logs at ERROR and attaches the exception being handled as the record’s exc_info. The formatter turns it into the traceback, so the entry says which call failed and where. It is log.error(..., exc_info=True) under a shorter name.

Request req-c4e117’s label fails: parcelpost answers 503. In the draft on the left, every frame logs str(err) with log.error and re-raises: three entries and no traceback, and an alert that counts errors counts three. Log it once, where you handle it: create_shipment catches CarrierError, logs it and answers 502. The frames below it let the error climb.

The exceptions tutorial’s chapter on the boundary shows where that place is in a whole program, and what to log for an expected failure.

SHIPYARD/API.PY: LOG WHERE YOU HANDLE IT
# shipyard/api.py
def create_shipment(request):
    order = load_order(request)
    try:
        label = carrier.create_label(order)
    except CarrierError:
        log.exception("label request failed")  # ERROR, with the traceback
        return Response(status=502)
    return Response(status=201, json=label)

COMMON QUESTIONS

%s or {} in the message?
The message template always uses % style. Formatter(style="{") changes only the formatter’s own format string, never your messages.
Can I attach an exception outside an except block?
Yes: log.error("label request failed", exc_info=err) takes the exception object itself and logs its traceback.

WHAT YOU NOW KNOW

  • One call builds a LogRecord holding your template, your values, the level, the time and the source line.
  • Pass values as arguments, so the message stays one fixed event and is merged only when a handler writes it.
  • Log an error once, where you handle it, with log.exception, so the traceback comes with it.
DEEP DIVE: helper functions and stacklevel · what a record costs · error trackers

Helper functions and stacklevel

A wrapper such as log_event(name, **fields) that calls log.info makes every record point at the wrapper: funcName is log_event and lineno its line. Pass stacklevel=2 (Python 3.8) and findCaller skips one more frame, so the record names the function that called the wrapper.

What a record costs

A call below the logger’s level costs one cached level check. Every call that passes it builds a record, even if a handler drops it later: findCaller walks the stack, and the record reads the thread, process and asyncio task names. In a hot path, setting logging.logThreads, logProcesses, logMultiprocessing and logAsyncioTasks to False skips those fields.

Error trackers

Tools such as Sentry read ERROR records through a logging integration and group repeats of one failure into one issue. Sentry’s Python SDK 3.0 (November 2026) changed its LoggingIntegration: event_level now defaults to None, so log records no longer become error events unless you set event_level=logging.ERROR.

Structured logs: JSON lines with named fields

Each line now has a fixed template and its values, but it is still a sentence. Finding every slow label takes a regular expression, a traceback arrives in the log tool as one entry per line, and 412 could be milliseconds or an order count. The part that decides what a line looks like can write data instead of a sentence. How do you write log lines a machine can search?

STEP 01 / 03

A JSON LINE IS ONE RECORD WITH NAMED FIELDS

Fig 5.1The accent keys answer the query directly; the text line needs a pattern.

A formatter is the object on a handler that turns a record into the text the handler writes, the last part before stdout. A handler without one writes %(message)s, and basicConfig uses %(levelname)s:%(name)s:%(message)s. shipyard’s handler, from chapter 03, uses %(asctime)s %(levelname)s %(name)s: %(message)s, which buries the values in a sentence.

Structured logging writes each record as named fields instead: one JSON object per record, one object per line, a format called JSON Lines. The log tool reads the keys, so carrier = "parcelpost" and duration_ms > 1000 needs no pattern. A traceback becomes one escaped string inside its line, so it stays one entry instead of one entry per line.

The time changes too. The default asctime is local time with no zone, 2026-12-02 14:03:07,512, which can’t be compared across servers in different zones. The JSON line writes UTC in ISO 8601 form, 2026-12-02T14:03:07.512Z. No call site changes; only the handler’s formatter does.

THE RECORD AS A TEXT LINE
2026-12-02 14:03:07,512 INFO shipyard.carrier: label created shp_10482 parcelpost 412 ms
THE SAME RECORD AS ONE JSON LINE, INDENTED HERE TO BE READ
{
  "time": "2026-12-02T14:03:07.512Z",
  "level": "INFO",
  "logger": "shipyard.carrier",
  "message": "label created",
  "shipment_id": "shp_10482",
  "carrier": "parcelpost",
  "duration_ms": 412
}
STEP 02 / 03

KEEP THE MESSAGE FIXED, PUT VALUES IN FIELDS

Fig 5.2Follow the three accent values from the call, onto the record, into the line.

log.info("label created", extra={...}) passes the values as extra: each key becomes an attribute of the record, and the JSON formatter writes it as a top-level key. The message names the event and never changes; the fields carry everything that varies. Name them in snake case with the unit in the name: duration_ms, not duration.

shipyard/logjson.py shows the mechanism in twenty lines. format(record) builds time, level, logger and message, adds every attribute a plain record doesn’t have, adds the traceback as exc_info, and returns json.dumps of the result. In configure_logging(), the formatter entry {"()": JsonFormatter} replaces the text format.

In production, use python-json-logger 4.2.0 instead of your own: pythonjsonlogger.json.JsonFormatter does the same, extra keys included, and dictConfig loads it with "()": "pythonjsonlogger.json.JsonFormatter". The old import path, pythonjsonlogger.jsonlogger, still works but warns with a DeprecationWarning.

THE VALUES AS NAMED FIELDS
log.info(
    "label created",
    extra={"shipment_id": shipment.id, "carrier": "parcelpost", "duration_ms": ms},
)
SHIPYARD/LOGJSON.PY: A JSON FORMATTER IN TWENTY LINES
# shipyard/logjson.py
import json
import logging
from datetime import UTC, datetime

# Every attribute a plain record has; anything else came from extra=.
STANDARD = set(vars(logging.makeLogRecord({}))) | {"message", "asctime"}


class JsonFormatter(logging.Formatter):
    def format(self, record):
        time = datetime.fromtimestamp(record.created, UTC)
        line = {
            "time": time.isoformat(timespec="milliseconds").replace("+00:00", "Z"),
            "level": record.levelname,
            "logger": record.name,
            "message": record.getMessage(),
        }
        line |= {k: v for k, v in vars(record).items() if k not in STANDARD}
        if record.exc_info:
            line["exc_info"] = self.formatException(record.exc_info)
        return json.dumps(line, default=str)


# In configure_logging(): add "json": {"()": JsonFormatter} under "formatters",
# and set "formatter": "json" on the stdout handler.
STDOUT: ONE RECORD PER LINE, THE TRACEBACK INSIDE ITS LINE
{"time": "2026-12-02T14:03:07.512Z", "level": "INFO", "logger": "shipyard.carrier", "message": "label created", "shipment_id": "shp_10482", "carrier": "parcelpost", "duration_ms": 412}
{"time": "2026-12-02T14:03:09.204Z", "level": "ERROR", "logger": "shipyard.api", "message": "label request failed", "exc_info": "Traceback (most recent call last):\n  File \"/app/shipyard/api.py\", line 5, in create_shipment\n  ...\nshipyard.carrier.CarrierError: parcelpost answered 503"}
STEP 03 / 03

STRUCTLOG BUILDS THE SAME LINE FROM KEY-VALUE CALLS

Fig 5.3Watch the dict gain a key at each processor; the last one turns it into a line.

structlog 26.1.0 is a library that skips templates and extra: log.info("label created", shipment_id=sid, ...) takes the fields as keyword arguments. structlog puts them in a dict, the event dict, and adds the first argument under the key event.

Then a chain of processors runs, each a function that takes the dict and returns it changed. merge_contextvars adds any context bound with bind_contextvars (chapter 06’s deep dive), add_log_level adds level, TimeStamper the UTC time, dict_tracebacks turns an exception into JSON data, and JSONRenderer writes the dict as one line.

You configure the chain once, at startup, as you do with dictConfig. structlog is the alternative in this tutorial. The main path stays the standard library with a JSON formatter, because every library you use already logs through logging.

STRUCTLOG: THE CHAIN AND ONE CALL
import logging

import structlog

structlog.configure(
    processors=[
        structlog.contextvars.merge_contextvars,  # request_id, chapter 06
        structlog.processors.add_log_level,
        structlog.processors.TimeStamper(fmt="iso", utc=True),
        structlog.processors.dict_tracebacks,
        structlog.processors.JSONRenderer(),
    ],
    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
    cache_logger_on_first_use=True,
)

log = structlog.get_logger()
log.info("label created", shipment_id="shp_10482", carrier="parcelpost", duration_ms=412)
WHAT JSONRENDERER WRITES
{"shipment_id": "shp_10482", "carrier": "parcelpost", "duration_ms": 412, "event": "label created", "level": "info", "timestamp": "2026-12-02T14:03:07.512408Z"}

COMMON QUESTIONS

python-json-logger or structlog?
python-json-logger changes only the formatter, so every existing logging call keeps working. structlog changes the calls too, and pays off when you bind context often (chapter 06).
Isn’t JSON hard to read in a terminal?
Use a console format when the output is a terminal and JSON otherwise. structlog’s docs switch on sys.stderr.isatty().

WHAT YOU NOW KNOW

  • A JSON formatter writes each record as one line of named fields, so the log tool queries keys instead of matching text.
  • Keep the message a fixed event name and put every varying value in extra, named with its unit.
  • structlog builds the same line from keyword arguments, passed through a chain of processors.
DEEP DIVE: UTC timestamps · one format for structlog and logging · Loguru

UTC timestamps

asctime comes from Formatter.formatTime, whose converter is time.localtime. The logging cookbook’s UTCFormatter sets converter = time.gmtime, so a text format writes UTC, though the text still carries no zone. The JSON formatter above builds its time from record.created with datetime.fromtimestamp(record.created, UTC) and isoformat(timespec="milliseconds"), then writes Z for +00:00.

One format for structlog and logging

structlog.stdlib.ProcessorFormatter is a logging.Formatter that runs structlog processors. Put it on the stdout handler. Records from logging, such as httpx’s, pass through foreign_pre_chain first. structlog’s own events reach the handler through logging, because wrap_for_formatter hands them over, so they pass the same levels and filters. Both end in the same renderer, and stdout gets one format.

ONE JSON FORMAT FOR STRUCTLOG’S EVENTS AND LOGGING’S RECORDS
import structlog

SHARED = [
    structlog.contextvars.merge_contextvars,
    structlog.stdlib.add_log_level,
    structlog.processors.TimeStamper(fmt="iso", utc=True),
]

FORMATTERS = {
    "json": {
        "()": structlog.stdlib.ProcessorFormatter,
        "foreign_pre_chain": SHARED,  # runs only on records from logging
        "processors": [
            structlog.stdlib.ProcessorFormatter.remove_processors_meta,
            structlog.processors.JSONRenderer(),
        ],
    },
}

structlog.configure(
    processors=[*SHARED, structlog.stdlib.ProcessorFormatter.wrap_for_formatter],
    logger_factory=structlog.stdlib.LoggerFactory(),
    wrapper_class=structlog.stdlib.BoundLogger,
)

Loguru

Loguru 0.8.0 gives you one ready-made logger instead of a tree of loggers: logger.add() attaches sinks instead of handlers, and serialize=True writes each message as JSON. A standard-library handler can be one of its sinks. Libraries such as httpx still log through logging, so their records reach Loguru only through an intercepting handler, which its README provides as InterceptHandler.

Context: every line of one request

shipyard now writes one JSON line per record, with a fixed message and named fields. At its busiest it serves 40 requests at once, so their lines arrive interleaved on stdout, and nothing on a line says which request wrote it. A request ID, one short ID written on every line of a request, would tell you. Passing it to every call by hand is easy to forget, and it never reaches the lines httpx writes. How do you find every line of one request?

STEP 01 / 02

A CONTEXT VARIABLE CARRIES THE REQUEST ID

Fig 6.1Read only the accent rows: one request’s lines, the library’s line included.

A filter is an object on a logger or a handler that runs for each record; it can drop the record or add fields to it. shipyard attaches one to its only handler, so it runs after propagation and before the formatter: your code, the module logger, its parent, the root, the handler with its filters, the formatter, stdout.

The ID it adds comes from a context variable, a contextvars.ContextVar that holds a separate value in each asyncio task and thread, so 40 requests at once don’t mix. The request handler sets it to the request ID, such as req-7f3a9c, when a request starts and resets it when the request ends. The filter copies it onto every record as record.request_id, and the JSON formatter writes it as a field.

Why the handler? A filter on a logger sees only the records logged on that logger itself. Records from child loggers and from libraries reach the root’s handler without passing any ancestor logger’s filters, so the handler is the one place every record passes, httpx’s included.

SHIPYARD/CONTEXT.PY: THE REQUEST ID ON EVERY RECORD
# shipyard/context.py
import logging
from contextvars import ContextVar

request_id_var = ContextVar("request_id", default="-")


class RequestIdFilter(logging.Filter):
    def filter(self, record):
        record.request_id = request_id_var.get()
        return True  # keep every record; this filter only adds a field


# shipyard/api.py: set it when a request starts, reset it when it ends
def handle(request):
    token = request_id_var.set(request.headers.get("X-Request-ID") or new_id())
    try:
        return route(request)
    finally:
        request_id_var.reset(token)


# In configure_logging(): "filters": {"request_id": {"()": RequestIdFilter}},
# and "filters": ["request_id"] on the stdout handler, not on a logger.
STEP 02 / 02

A TRACE ID LINKS A LINE TO ITS TRACE

Fig 6.2The accent ID is the same string in the log line and in the trace.

A trace ID is the ID OpenTelemetry gives every span of one request’s trace, the timed operations it ran through, as the tracing tutorial shows. If shipyard is traced, opentelemetry-instrumentation-logging can put the current trace and span IDs on every record as otelTraceID and otelSpanID.

It is opt-in since version 0.61b0: call LoggingInstrumentor().instrument(inject_trace_context=True) once at startup, and your format stays as it was. The JSON formatter writes the two attributes as trace_id and span_id, so the line carries the same 32-character ID as the trace, and the log tool can go from one to the other.

TRACE AND SPAN IDS ON EVERY RECORD, FROM OPENTELEMETRY
from opentelemetry.instrumentation.logging import LoggingInstrumentor

# Adds otelTraceID and otelSpanID to every record; your format stays.
# It also sends records to OpenTelemetry unless
# OTEL_PYTHON_LOG_AUTO_INSTRUMENTATION=false.
LoggingInstrumentor().instrument(inject_trace_context=True)

# In JsonFormatter.format(), name them the way your log tool links them.
RENAME = {"otelTraceID": "trace_id", "otelSpanID": "span_id"}

COMMON QUESTIONS

Where does the request ID come from?
Reuse the caller’s if it sends one in X-Request-ID, so the shop’s lines and yours match. Otherwise generate one, and return it in the response header.
What about background jobs?
Set the variable to the job’s ID when each job starts and reset it when the job ends, the same way.

WHAT YOU NOW KNOW

  • A ContextVar holds the current request’s ID, such as req-7f3a9c, separately for each asyncio task and thread.
  • A filter on the handler copies it onto every record, so httpx’s lines carry it too.
  • With OpenTelemetry, trace_id and span_id land on each line as well, linking it to the request’s trace.
DEEP DIVE: LoggerAdapter · structlog’s contextvars · clearing context

LoggerAdapter

logging.LoggerAdapter(log, {"request_id": rid}) adds fixed fields to the calls made through it. By default it replaces a call’s own extra with its dictionary; merge_extra=True (Python 3.13) merges the two, the call’s keys winning. It changes only calls made through the adapter, so httpx’s lines never get the field. That is why this chapter uses a filter.

Context in structlog

structlog.contextvars.bind_contextvars(request_id=rid) stores the value in a context variable, and the merge_contextvars processor, first in chapter 05’s chain, copies it into every event. bound_contextvars(...) does the same as a with block and restores the previous values when the block ends.

structlog’s own loggers bypass logging, so httpx’s records still need the filter, or ProcessorFormatter with merge_contextvars in its foreign_pre_chain, as chapter 05’s deep dive sets it up.

Clearing context

Reset the variable when the request ends, as request_id_var.reset(token) does in the finally block above. In a server that runs requests on reused threads, a value never reset stays on that thread, and the next request’s first lines carry the old ID. structlog’s docs suggest clear_contextvars() early in each request for the same reason.

What not to log

Every line shipyard writes is copied to the log platform, kept for months and readable by more people than the database is. One debug line that prints a whole request, or httpx printing a URL, can put a carrier key or a customer’s email in all of those places. What must never reach a log, and how do you keep it out?

STEP 01 / 02

LOG IDS, NOT SECRETS OR PERSONAL DATA

Fig 7.1The accent row is safe to log as it is; the red rows never reach a line.

Redaction means masking or removing secret and personal values before a line is written. shipyard does it in a second filter on the same handler, after the request ID filter: your code, the module logger, its parent, the root, the handler with both filters, the formatter, stdout. It is the last check before a line leaves the process.

The first defence is not passing those values at all. The OWASP Logging Cheat Sheet lists data that “should usually not be recorded directly in the logs, but instead should be removed, masked, sanitized, hashed, or encrypted”: session IDs, access tokens, passwords, keys, payment card data and sensitive personal data (PII). Log the ID of a thing, order_id, never its contents, a whole request or its headers.

RedactFilter masks attributes by name (api_key, authorization, password, card_number), shortens an email field to a***@example.com, and replaces key= and token= values in the message text. On the handler, it covers library lines such as httpx’s too.

SHIPYARD/REDACT.PY: THE LAST CHECK BEFORE THE FORMATTER
# shipyard/redact.py
import logging
import re

SECRET_FIELDS = {"api_key", "authorization", "password", "card_number"}
EMAIL = re.compile(r"([^@\s])[^@\s]*@")
QUERY_SECRET = re.compile(r"\b(key|token)=[^&\s\"]+")


class RedactFilter(logging.Filter):
    def filter(self, record):
        for name in SECRET_FIELDS & set(vars(record)):
            setattr(record, name, "[redacted]")
        if isinstance(getattr(record, "email", None), str):
            record.email = EMAIL.sub(r"\1***@", record.email)  # a***@example.com
        message = QUERY_SECRET.sub(r"\1=[redacted]", record.getMessage())
        record.msg, record.args = message, None
        return True
STEP 02 / 02

A NEWLINE IN INPUT CAN FORGE A LOG LINE

Fig 7.2The red panel holds two lines from one call; the accent panel holds one.

Log injection, or log forging, is input that makes a text log show a line nobody logged. The shop sends a reference that shipyard logs with log.info("shipment requested for %s", reference). A text formatter writes the newline inside it as it is, so the rest of the value reads as a second line: a refund approval with a real time and logger.

CWE-117 names this weakness “Improper Output Neutralization for Logs”, with “Log forging” as an alternate term. A JSON formatter writes the newline as the two characters \n inside one string, so the input can’t add a line. OWASP’s Log Injection section recommends it: “use structured log formats, such as JSON”. Cap the length of logged input as well.

A TEXT LOG: TWO LINES FROM ONE CALL
2026-12-02 14:03:08,001 INFO shipyard.api: shipment requested for ord_88213
2026-12-02 14:03:08,001 INFO shipyard.api: refund approved ord_88213
THE SAME CALL IN A JSON LOG: ONE LINE
{"time": "2026-12-02T14:03:08.001Z", "level": "INFO", "logger": "shipyard.api", "message": "shipment requested for ord_88213\n2026-12-02 14:03:08,001 INFO shipyard.api: refund approved ord_88213"}

COMMON QUESTIONS

Isn’t hashing an email enough?
Not always. A hash of a random session cookie is safe, but anyone can hash a list of known emails and match the results. Mask the email, or log the customer’s internal ID instead.
How long should logs be kept?
As long as the investigations you run need, and no longer. Personal data in logs falls under the same retention rules as the same data in the database.

WHAT YOU NOW KNOW

  • Log IDs such as ord_88213 and outcomes; keys, tokens, passwords, card data and personal data stay out of every line.
  • A redaction filter on the handler masks known fields such as api_key and email, in library lines too.
  • A JSON formatter escapes a newline in the input, so a customer can’t write a fake line into the log.
DEEP DIVE: sampling noisy lines · Python warnings in the log

Sampling noisy lines

A filter can also thin out one repetitive event: keep one record in N for a given record.msg and drop the rest by returning False. Key it on the template, not the merged message, so every shipment’s carrier request built counts as one event. Sample only DEBUG and INFO; a dropped WARNING or ERROR is the line you needed.

Python warnings in the log

logging.captureWarnings(True) sends what warnings.warn(...) would print to stderr to the logger py.warnings at WARNING instead, so warnings arrive in the same JSON stream as every other line, with the request ID when one is set. Each record’s message is the whole formatted warning, file and line included, so it is not one fixed template.

The whole picture

Here is the path again, every part keyed to a row of the table below.

Find a number on the figure, then its row below: what the part does, where you set it and what it checks.

ONE LINE, END TO END

The carrier module calls log.info("label created", extra={…}) for shipment shp_10482. Its logger (1) passes the INFO level (4) and builds a record (5), which climbs past shipyard (2) to the root (6). The handler (7) writes it after its filters add request_id=req-7f3a9c (8) and mask what must not be written (9), and the formatter (10) makes it one JSON line on stdout (11).

  1. 1shipyard.carrier, the module logger

    names the module that reports each event

    where it is set
    getLogger(__name__) at the top of the module
    checks
    its effective level, before any record is built
    when wrong
    lines that say root instead of the module that wrote them
  2. 2shipyard, the parent logger

    lets one setting cover every module in the package

    where it is set
    created by the dotted names below it
    checks
    nothing for its children’s records; only its own handlers run
    when wrong
    a level set here that child lines seem to ignore
  3. 3httpx, a library’s logger

    carries the library’s own events in the same tree

    where it is set
    created by the library, configured by you
    checks
    its own effective level
    when wrong
    one request line per call flooding the log at INFO
  4. 4level

    drops records below a threshold

    where it is set
    level on a logger or handler in dictConfig
    checks
    the record’s level against the logger’s, then each handler’s
    when wrong
    INFO lines missing, or DEBUG volume billed in production
  5. 5LogRecord

    carries the template, values, time, source line and exception

    where it is set
    built by the logger for every call that passes its level
    checks
    nothing; it only carries data to the handlers
    when wrong
    messages with values baked in, or an error with no traceback
  6. 6root logger and propagation

    collects every record at the top of the tree

    where it is set
    the root key in dictConfig
    checks
    each handler’s level on the way up, never an ancestor logger’s level
    when wrong
    every line printed twice when two loggers on one path have handlers
  7. 7handler

    writes each record that reaches it to stdout

    where it is set
    attached to the root logger, once, at startup
    checks
    its own level, then its filters
    when wrong
    no output at all, or lines in a file nobody collects
  8. 8request ID filter

    adds the current request’s ID to every record

    where it is set
    on the handler, so library lines get it too
    checks
    nothing; it copies a context variable onto the record
    when wrong
    lines of one request you can’t pick out from forty others
  9. 9redaction filter

    masks secrets and personal data before the line is written

    where it is set
    on the handler, as the last check
    checks
    field names such as api_key and email, and keys in URLs
    when wrong
    carrier keys or customer emails searchable in the log tool
  10. 10formatter

    turns each record into one JSON line of named fields

    where it is set
    on the handler
    checks
    nothing; it only decides the shape of the text
    when wrong
    a regular expression to find a value, or tracebacks split into many entries
  11. 11stdout

    carries the lines out of the process to the platform

    where it is set
    the handler’s stream
    checks
    nothing; the platform collects whatever arrives
    when wrong
    plain print() text mixed in among the JSON lines
  12. ·dictConfig

    sets levels, handlers, filters and formatters in one place

    where it is set
    configure_logging(), the first thing main() calls
    checks
    nothing; it runs once at startup
    when wrong
    module loggers silenced because disable_existing_loggers stayed true
  13. ·your code

    asks for a record with a fixed message and named fields

    where it is set
    every module, through its own logger
    checks
    nothing
    when wrong
    f-strings for messages, secrets in lines, one error logged three times

THREE THINGS TO KEEP

  • A log call makes a record that climbs the tree of named loggers to the handlers at the root.
  • Write a fixed message and put the values in named fields, so a machine can search every line.
  • Logs are copied and kept for months. A password or a customer’s email in one line is a leak.
Read next. Exceptions in Python for where an error should be caught and logged, and AI agent tracing for the traces your log lines can link to.

Name the event, name the fields, and leave the secrets out.