Skip to content

Lesson 53 of 59Production

Logging and Observability

Configure logging properly, emit structured JSON with request IDs, add metrics, traces and error tracking, and alert on what users feel.

18 min read0/5 questions

At 3 a.m. a customer reports that checkout "just spins". Your API runs as six containers behind a load balancer, and you cannot attach a debugger to any of them. Everything you will ever know about that failed request is what your code chose to record while it ran. Observability is the practice of recording the right things, in a shape you can search, so you can answer questions about production you did not think to ask in advance. This lesson goes past the basics from the errors and middleware lesson and builds the full picture: configured logging, structured logs, correlation, metrics, traces, error tracking and alerts.

Four kinds of signal

Each signal answers a different question, and mature teams use all of them together.

SignalAnswersExample
LogsWhat exactly happened in this one request?order failed: card declined, order_id=812
MetricsHow is the system doing overall, over time?412 requests/s, 0.3% errors, p95 180 ms
TracesWhere did the time go inside one request?20 ms in auth, 900 ms waiting on the payment API
ErrorsWhich exceptions are new, and how often?KeyError in apply_coupon, 57 times since the 14:02 deploy

Logs are detailed but expensive to store and search. Metrics are cheap numbers you can keep for months and graph. Traces sit in between: a structured timeline for a sample of requests. Error trackers group identical exceptions so one bug shows up as one issue, not ten thousand log lines.

Match the pairs0/4 matched

Match each question to the signal that answers it best.

Choose an item, then its match on the other side.

Configure logging once, log everywhere

The logging Module in the Python course covers this in depth; here is the setup for an API. Python's logging module has three pieces. Loggers are what your code calls, named after the module (logging.getLogger(__name__)), so they form a tree: app.api.orders is a child of app. Handlers decide where records go (stdout, a file). Formatters decide what each line looks like. Library code only ever creates loggers. The application configures handlers and formatters once, at startup.

app/core/logging.py
import logging.config
 
 
def setup_logging(level: str = "INFO") -> None:
    logging.config.dictConfig({
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "plain": {"format": "%(asctime)s %(levelname)s %(name)s %(message)s"},
        },
        "handlers": {
            "stdout": {"class": "logging.StreamHandler", "formatter": "plain", "stream": "ext://sys.stdout"},
        },
        "root": {"level": level, "handlers": ["stdout"]},
        "loggers": {
            "sqlalchemy.engine": {"level": "WARNING"},   # set INFO to see every SQL statement
            "httpx": {"level": "WARNING"},
        },
    })
app/services/orders.py
import logging
 
logger = logging.getLogger(__name__)
 
 
def place_order(order_id: int) -> None:
    logger.info("placing order", extra={"order_id": order_id})

Call setup_logging(settings.log_level) in your lifespan handler or at the top of main.py. A few habits matter:

  • Levels mean something. DEBUG is for development detail. INFO is normal business events (order placed, user signed up). WARNING is "unexpected but handled" (a retry, a deprecated parameter). ERROR means a request or job failed. CRITICAL means the service itself is in trouble.
  • Log to stdout. In containers, the platform collects stdout. Writing to files inside a container loses them when it restarts.
  • Use logger.exception(...) inside except. It logs at ERROR and attaches the traceback.
  • Pass values as data, not baked into the message. logger.info("placing order", extra={...}) lets tools filter on order_id. An f-string turns it into unsearchable text.
Quick check
A call to the payment provider times out, your code retries, and the second attempt succeeds. Which level fits the log line for the first failure?
Need a nudge? A hint rules out a wrong answer.

Structured JSON logs and request IDs

Plain text is fine on your laptop. In production you want one JSON object per line, so CloudWatch, Datadog or Grafana Loki can filter by any field: status >= 500, user_id = 42, request_id = "abc123".

The request id is what makes logs usable. Middleware assigns one per request (or reuses the X-Request-ID the load balancer sent). If every line logged during that request carries it, one search shows the request's whole story. The trick is getting the id into log lines from deep inside a service without passing it through every function. Python's contextvars solve this: a context variable holds a different value per request, even with many requests interleaved on one event loop.

Pythonjson_logs.py
import contextvarsimport jsonimport loggingimport sys request_id_var = contextvars.ContextVar("request_id", default="-") class JsonFormatter(logging.Formatter): def format(self, record): entry = { "level": record.levelname, "logger": record.name, "msg": record.getMessage(), "request_id": request_id_var.get(), } entry.update(getattr(record, "fields", {})) return json.dumps(entry) handler = logging.StreamHandler(sys.stdout)handler.setFormatter(JsonFormatter())logging.basicConfig(level=logging.INFO, handlers=[handler], force=True)logger = logging.getLogger("app.orders") def place_order(order_id): # deep inside a service: no request id passed in logger.info("placing order", extra={"fields": {"order_id": order_id}}) def handle_request(request_id, order_id): token = request_id_var.set(request_id) # what the middleware does try: place_order(order_id) finally: request_id_var.reset(token) handle_request("req-a1", 812)handle_request("req-b2", 813)logger.info("startup complete") # outside any request
Output
Press Run (⌘ Enter) to see what happens.

You could build on that formatter, but most teams use structlog, which does the same job with less code. It has built-in support for context variables, so your middleware binds the request id once and every log call picks it up:

app/main.py
import uuid
 
import structlog
from fastapi import FastAPI, Request
 
structlog.configure(
    processors=[
        structlog.contextvars.merge_contextvars,      # pull in bound request fields
        structlog.processors.add_log_level,
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.format_exc_info,
        structlog.processors.JSONRenderer(),
    ]
)
logger = structlog.get_logger()
app = FastAPI()
 
 
@app.middleware("http")
async def bind_request_context(request: Request, call_next):
    request_id = request.headers.get("x-request-id") or uuid.uuid4().hex
    structlog.contextvars.clear_contextvars()
    structlog.contextvars.bind_contextvars(request_id=request_id, path=request.url.path)
    response = await call_next(request)
    response.headers["X-Request-ID"] = request_id
    logger.info("request finished", status=response.status_code)
    return response

Anywhere in the app, logger.info("order placed", order_id=812) now prints JSON with request_id, path, level and timestamp attached. In development you can swap JSONRenderer for structlog's console renderer to get coloured, readable output.

Correlation goes one step further. When your API calls another service, forward the request id in a header. If that service logs it too, one id follows the work across your whole system. Tracing, below, formalises exactly this idea.

Metrics and traces with OpenTelemetry

Metrics are numbers aggregated over time. Three kinds cover most needs: a counter only goes up (requests served, orders placed), a gauge goes up and down (queue length, open connections), and a histogram records a distribution (request duration). For an HTTP service, start with the RED method: Rate of requests, Errors, and Duration, broken down by route and status.

A trace is the timeline of one request. It is made of spans: one for the whole request, children for the database query, the Redis call and the HTTP call to the payment provider. Every span shares a trace id, and the id travels between services in a standard traceparent header, so a request that touches four services shows up as one tree.

OpenTelemetry (OTel) is the vendor-neutral standard for producing metrics, traces and logs. You instrument your code once with the OTel SDK and its instrumentation packages for FastAPI, SQLAlchemy and httpx, and an exporter sends the data (usually over the OTLP protocol) to a collector or straight to a backend such as Grafana, Honeycomb, Datadog or Jaeger. Switching vendors means changing exporter config, not code. Instrumentation packages create spans for incoming requests and outgoing calls automatically; you add your own spans around interesting business logic. Setup details change between releases, so follow the OpenTelemetry Python docs for the current packages and configuration.

Where telemetry goes
FastAPI app: structlog, OTel SDKFastAPI appstructlog, OTel SDKstdout: JSON log linesstdoutJSON log linesOTel Collector: batches, exportsOTel Collectorbatches, exportsLog store: Loki, CloudWatchLog storeLoki, CloudWatchMetrics + traces: Grafana, DatadogMetrics + tracesGrafana, DatadogSentry: grouped exceptionsSentrygrouped exceptionslogsplatform shipsOTLPexceptions

Your app writes JSON logs to stdout. The platform ships them to a searchable store; the app never knows where they end up.

1/3

Error tracking with Sentry

An error tracker catches unhandled exceptions, groups identical ones into a single issue, and tells you when a new one appears. Sentry is the common choice and its SDK detects FastAPI automatically:

app/main.py
import sentry_sdk
 
sentry_sdk.init(
    dsn=settings.sentry_dsn,           # from the environment, never hardcoded
    environment=settings.environment,  # "production", "staging"
    traces_sample_rate=0.1,            # also record 10% of requests as traces
)

Tag each event with the release (your git commit SHA) so you can see that an issue started with a specific deploy.

Health checks and what to alert on

The deploying lesson covers liveness (/health, never touches the database) and readiness (/ready, checks dependencies with a short timeout). Two observability notes: filter health check requests out of your access logs, since a load balancer hitting them every few seconds buries the interesting lines; and an external uptime check that calls your public URL catches problems your own infrastructure cannot see, like DNS or certificate expiry.

Alerts wake people up, so be strict. Alert on symptoms users feel: error rate above a threshold, p95 or p99 latency too high, the uptime check failing, a queue that keeps growing. Do not page on causes like "CPU at 80%" if users are fine. Put those on a dashboard. Every alert should be actionable; an alert people learn to ignore is worse than none.

Use percentiles, not averages, for latency. The p95 is the time 95% of requests finish under. An average hides the slow tail that real users hit:

Pythonpercentiles.py
import statistics # 100 requests: most are fast, a few hit a slow database querylatencies_ms = [40] * 90 + [60] * 5 + [1800] * 5 def percentile(values, p): ordered = sorted(values) index = max(0, round(p / 100 * len(ordered)) - 1) return ordered[index] print("mean:", statistics.mean(latencies_ms), "ms")print("p50: ", percentile(latencies_ms, 50), "ms")print("p95: ", percentile(latencies_ms, 95), "ms")print("p99: ", percentile(latencies_ms, 99), "ms")
Output
Press Run (⌘ Enter) to see what happens.

The mean of 129 ms looks healthy. The p99 says one request in a hundred takes nearly two seconds, and a user who makes twenty requests per visit will very likely hit one.

Predict the outputPython

Using percentile from above, what does this print?

print(percentile([10, 20, 30, 40, 1000], 50))
Need a nudge? Hints walk you through it.
Quick check
Which of these is the best alert to page an on-call engineer at night?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

An alert fires: p95 latency on POST /orders has tripled. Order a sensible investigation.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
structured logging
Writing each log line as data (usually one JSON object) so tools can filter and aggregate by field.
request id
A unique id attached to every log line for one request, and forwarded to other services, to tie events together.
RED metrics
Rate, Errors and Duration: the three core metrics for any request-serving service.
trace and span
A trace is one request's timeline across services; spans are its timed steps, linked by a shared trace id.
OpenTelemetry
The vendor-neutral standard and SDKs for producing metrics, traces and logs and exporting them to any backend.
p95 latency
The time within which 95% of requests finish. Shows the slow tail that an average hides.
error tracker
A service like Sentry that captures exceptions with context and groups duplicates into issues.