Skip to content

Repository files navigation

logs-fastapi

Structured JSON request logging for FastAPI, built on structlog. One line of JSON per request — method, path, request id, real status code, duration — plus context-merged handler logs and a traceback line on unhandled exceptions.

Install

uv add logs-fastapi

Usage

from fastapi import FastAPI
from logs_fastapi.middleware import install

app = FastAPI()
install(app)  # idempotent

Every request then emits request.started / request.completed as JSON, and any structlog line inside a handler automatically carries the request context:

{"request_id": "3f1a...", "method": "GET", "path": "/", "status_code": 200,
 "duration_ms": 1.2, "timestamp": "2026-08-09T12:00:00Z", "event": "request.completed"}

Features

  • Request-scoped contextrequest_id, trace_id/span_id (W3C traceparent aware), method, path, query, client merged into every log line via contextvars; nothing leaks between requests.
  • Real status codes — captured from the ASGI send, streaming-safe; 499 on client disconnect (logged, cancellation semantics preserved).
  • Header redaction by defaultauthorization, cookie, set-cookie log as REDACTED; extensible via redact_headers (trust boundary).
  • Custom 500 handler without losing logs — own the failure response; request.failed with traceback is always logged first.
  • on_completed hooks — react to every request outcome, e.g. Prometheus counters; a broken hook is logged, never fatal.
  • Zero config, still tunable — JSON via orjson, LOG_LEVEL env var, request-body logging (on by default, off via log_request=False).

Documentation

Development

uv sync
make ci   # full CI suite

About

Structured, contextualized JSON request logging for FastAPI

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages