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.
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.
| Signal | Answers | Example |
|---|---|---|
| Logs | What exactly happened in this one request? | order failed: card declined, order_id=812 |
| Metrics | How is the system doing overall, over time? | 412 requests/s, 0.3% errors, p95 180 ms |
| Traces | Where did the time go inside one request? | 20 ms in auth, 900 ms waiting on the payment API |
| Errors | Which 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 each question to the signal that answers it best.
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.
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"},
},
})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.
DEBUGis for development detail.INFOis normal business events (order placed, user signed up).WARNINGis "unexpected but handled" (a retry, a deprecated parameter).ERRORmeans a request or job failed.CRITICALmeans 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(...)insideexcept. It logs atERRORand attaches the traceback. - Pass values as data, not baked into the message.
logger.info("placing order", extra={...})lets tools filter onorder_id. An f-string turns it into unsearchable text.
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.
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:
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 responseAnywhere 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.
Your app writes JSON logs to stdout. The platform ships them to a searchable store; the app never knows where they end up.
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:
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:
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.
Using percentile from above, what does this print?
print(percentile([10, 20, 30, 40, 1000], 50))
An alert fires: p95 latency on POST /orders has tripled. Order a sensible investigation.
- Tap the steps below in the right order.
- 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.