Skip to main content

Data and monitoring · Intermediate · 22 min

Write structured JSON logs in Python with structlog

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian) · structlog 26.1.0 · FastAPI 0.165.0

You will switch a FastAPI app to structlog 26.1, ending with one JSON object per line that carries a request ID, the route, the OpenTelemetry trace ID and redacted secrets, plus readable output for development and jq queries that answer real questions.

On this page

A log line like Order placed for ada@example.com, total 54000.00 is fine for a person reading a terminal. It is poor for a machine. To find every slow checkout, or every line from one failing request, a log search tool has to guess where the order number ends and the email begins. Structured logging fixes that: each line is a JSON object with named fields, so tools filter and group by field instead of by pattern.

In this tutorial you take a small FastAPI shop API and move its logging to structlog, a Python library built around one idea: a log entry is a dictionary that passes through a chain of small functions, called processors, before it is written out. You configure structlog to sit on top of the standard logging module, so lines from Uvicorn and other libraries come out in the same JSON shape as yours. Then you bind a request ID and the route to every line with context variables, add the OpenTelemetry trace ID, hide tokens and email addresses, keep a readable format for development, and query the result with jq.

If the standard logging module is new to you, start with logging properly in Python with the logging module. This tutorial assumes you know what loggers, handlers and levels are.

Step 1 · Create the project

Install curl and jq, make a folder for the demo and create a virtual environment with Python 3.15. Pin the packages so the output you see matches this page:

Bash
sudo apt update
sudo apt install -y curl jq
mkdir -p ~/structlog-demo
cd ~/structlog-demo
python3.15 -m venv .venv
.venv/bin/pip install "structlog==26.1.0" "fastapi==0.165.0" "uvicorn==0.54.0" "opentelemetry-sdk==1.45.2"

On macOS, run brew install jq instead of the two apt lines. structlog has no required dependencies of its own. FastAPI 0.165 already depends on opentelemetry-api; the SDK adds the part that creates real trace IDs.

Check it worked

Bash
.venv/bin/python -c "from importlib.metadata import version as v; print(v('structlog'), v('fastapi'), v('opentelemetry-sdk'))"

The command prints 26.1.0 0.165.0 1.45.2.

Step 2 · Write two processors of your own

A structlog processor is a plain function. It receives the logger, the name of the method that was called (info, warning and so on) and the event dictionary, and returns the dictionary, changed or not. That makes custom behaviour short to write and easy to test without any logging set up at all.

You need two. add_trace_ids asks OpenTelemetry for the span that is active right now and, if there is one, adds its trace ID and span ID in the usual hexadecimal form. That is the field that lets you jump from a log line to the matching trace. redact walks the dictionary and replaces the value of any key that looks secret (password, token, authorization and similar) with [REDACTED], and replaces anything that looks like an email address inside text with [EMAIL].

Create log_processors.py:

Bash
cat > log_processors.py <<'PY'
import re

from opentelemetry import trace

SENSITIVE_WORDS = ("password", "token", "secret", "authorization", "cookie", "api_key")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")


def add_trace_ids(logger, method_name, event_dict):
    """Add the current OpenTelemetry trace and span ids, if there is a span."""
    context = trace.get_current_span().get_span_context()
    if context.is_valid:
        event_dict["trace_id"] = format(context.trace_id, "032x")
        event_dict["span_id"] = format(context.span_id, "016x")
    return event_dict


def _scrub(key, value):
    if any(word in key.lower() for word in SENSITIVE_WORDS):
        return "[REDACTED]"
    if isinstance(value, dict):
        return {k: _scrub(k, v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [_scrub(key, v) for v in value]
    if isinstance(value, str):
        return EMAIL.sub("[EMAIL]", value)
    return value


def redact(logger, method_name, event_dict):
    """Hide secrets by key name and email addresses anywhere in text."""
    return {key: _scrub(key, value) for key, value in event_dict.items()}
PY

The key match is a substring match, so api_token and session_cookie are caught too. It also hides an innocent field such as tokens_used; rename that field rather than weaken the rule. Treat the processor as a safety net: the first defence is not passing secrets to a log call at all.

Now write a small script that calls both functions directly with plain dictionaries:

Bash
cat > check_processors.py <<'PY'
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider

from log_processors import add_trace_ids, redact

print(redact(None, "info", {
    "event": "signup_received",
    "password": "hunter2-demo",
    "headers": {"Authorization": "Bearer demo-value", "accept": "*/*"},
    "note": "Reply to ada.obi@example.com.ng today",
}))

print(add_trace_ids(None, "info", {"event": "outside_a_span"}))

trace.set_tracer_provider(TracerProvider())
with trace.get_tracer("check").start_as_current_span("demo"):
    inside = add_trace_ids(None, "info", {"event": "inside_a_span"})
print(sorted(inside), len(inside["trace_id"]), len(inside["span_id"]))
PY
.venv/bin/python check_processors.py

Check it worked

The output is three lines:

Text
{'event': 'signup_received', 'password': '[REDACTED]', 'headers': {'Authorization': '[REDACTED]', 'accept': '*/*'}, 'note': 'Reply to [EMAIL] today'}
{'event': 'outside_a_span'}
['event', 'span_id', 'trace_id'] 32 16

Outside a span nothing is added; inside one you get a 32-character trace ID and a 16-character span ID.

Step 3 · Configure structlog on top of the standard library

You could let structlog print on its own, but then lines from Uvicorn, FastAPI and any library that uses logging would stay plain text. The better set-up sends structlog's events into logging and gives the standard library's single handler a structlog formatter, ProcessorFormatter. Every line, whoever wrote it, then passes through the same processors and comes out in the same shape.

Two lists do the work. shared runs on every line: it merges in context variables (the next step uses them), adds the level and logger name, stamps an ISO 8601 time in UTC, and adds the trace IDs. The formatter's own list runs last: it removes structlog's internal keys, turns an exception into text, redacts, and renders. The LOG_FORMAT environment variable picks the renderer: JSON by default, a readable console format when it is console. LOG_LEVEL sets the threshold.

Create logging_setup.py:

Bash
cat > logging_setup.py <<'PY'
import logging
import os
import sys

import structlog

from log_processors import add_trace_ids, redact


def configure_logging():
    log_format = os.environ.get("LOG_FORMAT", "json")
    log_level = os.environ.get("LOG_LEVEL", "INFO").upper()

    # Run on every line, from structlog or from the standard library.
    shared = [
        structlog.contextvars.merge_contextvars,
        structlog.stdlib.add_log_level,
        structlog.stdlib.add_logger_name,
        structlog.processors.TimeStamper(fmt="iso", utc=True, key="timestamp"),
        add_trace_ids,
    ]

    if log_format == "console":
        renderer = structlog.dev.ConsoleRenderer(colors=sys.stdout.isatty())
        before_render = []
    else:
        renderer = structlog.processors.JSONRenderer()
        before_render = [structlog.processors.format_exc_info]

    structlog.configure(
        processors=[
            structlog.stdlib.filter_by_level,
            *shared,
            structlog.stdlib.PositionalArgumentsFormatter(),
            structlog.processors.StackInfoRenderer(),
            structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
        ],
        logger_factory=structlog.stdlib.LoggerFactory(),
        wrapper_class=structlog.stdlib.BoundLogger,
        cache_logger_on_first_use=True,
    )

    formatter = structlog.stdlib.ProcessorFormatter(
        foreign_pre_chain=shared,
        processors=[
            structlog.stdlib.ProcessorFormatter.remove_processors_meta,
            *before_render,
            redact,
            renderer,
        ],
    )

    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(formatter)
    root = logging.getLogger()
    root.handlers = [handler]
    root.setLevel(log_level)
PY

foreign_pre_chain is the list applied to lines that did not come from structlog, which is how a Uvicorn message gets a level, timestamp and request ID too. Logs go to standard output, one line per event. That is what container platforms, systemd's journal and log shippers such as Grafana Alloy expect to collect; the app does not manage log files.

format_exc_info is only in the JSON chain. It turns a traceback into a single string field, so a multi-line traceback stays inside one JSON line. The console renderer formats tracebacks itself.

Try it with a script that logs from structlog, from a plain standard-library logger, and from inside an except block:

Bash
cat > try_logging.py <<'PY'
import logging

import structlog

from logging_setup import configure_logging

configure_logging()

log = structlog.get_logger("shop.try")
log.info("stock_checked", product_id=2, in_stock=14)
log.debug("cache_details", hits=3)

logging.getLogger("thirdparty.client").warning("retrying in %s seconds", 2)

try:
    1 / 0
except ZeroDivisionError:
    log.exception("discount_failed", product_id=2)
PY
.venv/bin/python try_logging.py | jq -c '{level, logger, event, timestamp}'

Check it worked

jq prints three objects, something like:

Text
{"level":"info","logger":"shop.try","event":"stock_checked","timestamp":"2026-11-26T09:14:03.512204Z"}
{"level":"warning","logger":"thirdparty.client","event":"retrying in 2 seconds","timestamp":"2026-11-26T09:14:03.512610Z"}
{"level":"error","logger":"shop.try","event":"discount_failed","timestamp":"2026-11-26T09:14:03.512671Z"}

The debug line is missing because the level is INFO. Run LOG_LEVEL=debug .venv/bin/python try_logging.py | jq -r .event and cache_details appears. Run .venv/bin/python try_logging.py | jq -r 'select(.exception) | .exception' | tail -1 to see the last line of the traceback, ZeroDivisionError: division by zero.

Bash
LOG_LEVEL=debug .venv/bin/python try_logging.py | jq -r .event
.venv/bin/python try_logging.py | jq -r 'select(.exception) | .exception' | tail -1

Step 4 · Bind the request context in a FastAPI app

Now the app. A middleware runs around every request. It clears any old context, takes the caller's X-Request-ID header or makes a new ID, and binds it with bind_contextvars along with the method and path. Because merge_contextvars is in the shared chain, every line logged while that request is handled, by any logger, gets those fields without you passing them. Context variables are per task, so two requests handled at the same time never mix their IDs. FastAPI copies the context into the thread pool where it runs ordinary def routes, so those lines get the fields too.

After the route has run, the middleware binds the route template (/api/products/{product_id}, not /api/products/2) so you can group requests by route, and writes one request_finished line. Its level follows the status: info for success, warning for a 4xx client error and error for a 5xx. An unhandled exception is logged with log.exception, which adds the traceback, and turned into a 500 response that still carries the request ID.

Agree the field names once and keep them across every service. This app uses:

  • event: what happened, in snake_case, past tense: order_placed, request_finished. Never a sentence with values baked in.
  • level, logger, timestamp: added by the processors, always lowercase level names and UTC time.
  • request_id, method, path, route, status: the request.
  • Units in the name: duration_ms, and money as whole minor units, total_minor (kobo, pesewas or cents), so nobody has to guess the currency scale or round floats.

Trace IDs take one line of set-up. FastAPI 0.165 opens an OpenTelemetry span for every HTTP request as soon as a tracer provider is configured, so setting the SDK's TracerProvider gives each request a real trace ID that add_trace_ids picks up. Nothing is exported yet; that comes in the tracing tutorial. The order route also starts a span of its own, place_order, so you can see a child span inside the request.

Create app.py:

Bash
cat > app.py <<'PY'
import time
import uuid

import structlog
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from pydantic import BaseModel

from logging_setup import configure_logging

configure_logging()
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer("shop")
log = structlog.get_logger("shop.api")

PRODUCTS = {1: {"name": "Shea butter", "price_minor": 250000}, 2: {"name": "Ankara tote", "price_minor": 1800000}}

app = FastAPI()


@app.middleware("http")
async def log_requests(request: Request, call_next):
    structlog.contextvars.clear_contextvars()
    request_id = request.headers.get("x-request-id") or uuid.uuid4().hex
    structlog.contextvars.bind_contextvars(
        request_id=request_id, method=request.method, path=request.url.path
    )
    started = time.perf_counter()
    try:
        response = await call_next(request)
    except Exception:
        log.exception("request_failed", status=500, duration_ms=elapsed_ms(started))
        response = JSONResponse({"detail": "Internal error", "request_id": request_id}, status_code=500)
        response.headers["x-request-id"] = request_id
        return response

    route = request.scope.get("route")
    structlog.contextvars.bind_contextvars(route=route.path if route else "unmatched")
    status = response.status_code
    if status >= 500:
        emit = log.error
    elif status >= 400:
        emit = log.warning
    else:
        emit = log.info
    emit("request_finished", status=status, duration_ms=elapsed_ms(started))
    response.headers["x-request-id"] = request_id
    return response


def elapsed_ms(started):
    return round((time.perf_counter() - started) * 1000, 1)


@app.get("/api/products/{product_id}")
def get_product(product_id: int):
    product = PRODUCTS.get(product_id)
    if product is None:
        raise HTTPException(status_code=404, detail="No such product")
    return product


class OrderIn(BaseModel):
    product_id: int
    quantity: int
    email: str


@app.post("/api/orders", status_code=201)
def place_order(order: OrderIn):
    with tracer.start_as_current_span("place_order"):
        product = PRODUCTS[order.product_id]
        order_id = uuid.uuid4().hex[:12]
        log.info(
            "order_placed",
            order_id=order_id,
            product_id=order.product_id,
            quantity=order.quantity,
            total_minor=product["price_minor"] * order.quantity,
            customer_email=order.email,
        )
    return {"order_id": order_id}


@app.get("/api/payments/check")
def check_payments():
    raise RuntimeError("payment provider unreachable")
PY

The customer_email field is deliberate: it is the kind of field that creeps into real code, and the redaction processor should catch it.

Uvicorn normally installs its own logging configuration, with its own text format and an access log. Start it from a small script that passes log_config=None, so Uvicorn's messages go to your root handler, and access_log=False, because request_finished replaces the access log. Create serve.py:

Bash
cat > serve.py <<'PY'
import os

import uvicorn

from app import app

if __name__ == "__main__":
    port = int(os.environ.get("PORT", "8000"))
    uvicorn.run(app, host="127.0.0.1", port=port, log_config=None, access_log=False)
PY

In the second terminal, from ~/structlog-demo, start the app. tee shows the lines and also keeps a copy in app.log for jq later:

Bash
.venv/bin/python serve.py | tee app.log

Check it worked

The second terminal shows Uvicorn's start-up messages as JSON, with "logger": "uvicorn.error" (Uvicorn's name for its general logger, not only errors). In your first terminal, fetch a product and look at the response headers:

Bash
curl -s -i http://127.0.0.1:8000/api/products/1

The response is 200 with an x-request-id header of 32 hex characters and the body {"name":"Shea butter","price_minor":250000}. A new line appears in the second terminal with "event": "request_finished", "status": 200, "route": "/api/products/{product_id}", the same request_id, and a trace_id.

Step 5 · Follow one request through the logs

Send a few requests that each exercise a different path: an order with your own request ID, a missing product, a crash and a path that matches no route. A mobile app or a front end can send X-Request-ID itself; when a customer reports a failed payment from a patchy mobile connection, support can quote the ID the app showed and you find the exact lines, even if the phone retried several times.

Bash
curl -s -H "X-Request-ID: demo-req-001" -H "Content-Type: application/json" \
  -d '{"product_id": 2, "quantity": 3, "email": "ada.obi@example.com"}' \
  http://127.0.0.1:8000/api/orders
echo
curl -s http://127.0.0.1:8000/api/products/99
echo
curl -s http://127.0.0.1:8000/api/payments/check
echo
curl -s http://127.0.0.1:8000/no-such-page
echo

The responses are an order ID, {"detail":"No such product"}, {"detail":"Internal error","request_id":"..."} and {"detail":"Not Found"}.

Now pick out the order request by its ID:

Bash
jq -c 'select(.request_id == "demo-req-001") | {event, customer_email, trace_id, span_id}' app.log

Check it worked

You see two lines, something like:

Text
{"event":"order_placed","customer_email":"[EMAIL]","trace_id":"0e720c247f146bcf993611eef2a3850f","span_id":"b98fb03c231608e6"}
{"event":"request_finished","customer_email":null,"trace_id":"0e720c247f146bcf993611eef2a3850f","span_id":"a65e318769a9bcb8"}

Both lines share the trace ID, because they belong to one request, but the span IDs differ: order_placed was logged inside the place_order child span. The email address was replaced with [EMAIL]. Confirm it never reached the log at all:

Bash
if grep -q "@example.com" app.log; then echo "email address leaked"; false; else echo "no email addresses in the log"; fi

It prints no email addresses in the log.

Step 6 · Answer questions with jq

With every line a JSON object, questions become one-line queries. First make sure the whole file parses, which is what a log shipper will do with it:

Bash
jq -c -R 'fromjson' app.log > /dev/null && echo "every line is JSON"

How many lines at each level?

Bash
jq -s -c 'group_by(.level) | map({level: .[0].level, lines: length})' app.log

What failed, where, and with which exception? The traceback is one string, so its last line is the exception type and message:

Bash
jq -r 'select(.level == "error") | [.timestamp, .event, .path, (.exception | split("\n") | last)] | @tsv' app.log

Requests and the slowest time per route:

Bash
jq -s -c '[.[] | select(.event == "request_finished")] | group_by(.route) | map({route: .[0].route, requests: length, slowest_ms: (map(.duration_ms) | max)})' app.log

Check it worked

The first command prints every line is JSON. The level count shows one error, two warning lines (the 404s) and the rest info. The error query prints one tab-separated row ending in RuntimeError: payment provider unreachable. The route summary lists /api/orders, /api/products/{product_id} with 2 requests and unmatched, each with a slowest_ms of a few milliseconds. The same queries work in LogQL once these lines are in Loki, because LogQL's json parser reads the same fields.

Step 7 · Keep readable output in development

JSON is for machines. While you work on the app, you want lines you can scan. Stop the app with Ctrl+C in the second terminal, then start it again with the console renderer on a second port:

Bash
LOG_FORMAT=console PORT=8001 .venv/bin/python serve.py | tee dev.log

Send it a request from the first terminal:

Bash
curl -s http://127.0.0.1:8001/api/products/1
echo

Check it worked

The second terminal shows a line something like:

Text
2026-11-26T09:20:41.395157Z [info     ] request_finished               [shop.api] duration_ms=1.5 method=GET path=/api/products/1 request_id=f2f733d6bfc94302a79bf1043b0f31dd route=/api/products/{product_id} span_id=093a3ec44bcab671 status=200 trace_id=8af377738d6bf70b3e56b4d222dffe8f

Colours appear when the output is a terminal and are switched off when it is piped, so files never fill with escape codes. Same processors, same fields, redaction included: only the renderer changed. Keep LOG_FORMAT=console to your own machine and leave production on the JSON default. If you pay for log storage or ship logs over a metered link, set LOG_LEVEL=warning for noisy services rather than deleting log calls.

Step 8 · Clean up

Stop the app with Ctrl+C in the second terminal. Then remove the demo folder, which holds the virtual environment, the code and both log files. curl and jq stay installed:

Bash
cd ~
rm -rf ~/structlog-demo

Check it worked

ls ~/structlog-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.