Skip to content

Middleware

middleware

Defines custom ASGI middleware for the FastAPI application

LoggingMiddleware

Pure-ASGI middleware that binds a request context and logs a summary line

What It Does
  • Assigns each HTTP request a short correlation id and records its method, path, client ip, and query string into REQUEST_CONTEXT, so every log line emitted while the request is handled can be tied back to it

  • Emits one request-summary line per request, replacing uvicorn's silenced access log

Why Pure ASGI
  • This is implemented as a pure-ASGI middleware (not BaseHTTPMiddleware) so that it never reads or buffers the request body

  • The streaming upload routes and the Server-Sent-Events endpoints therefore pass through untouched

Operations Per Request
  • Builds the request context (correlation id + method + path + client ip + query parameters)

  • Stores it in REQUEST_CONTEXT, keeping the reset token so the previous context is restored after

  • Wraps the ASGI send channel to capture the response status from the http.response.start message, without touching the body

  • Always logs a single summary line and resets the context, even when the wrapped app raises

__call__(scope, receive, send) async

Binds the request context for HTTP scopes and logs the summary

Non-HTTP scopes (lifespan, websocket) pass straight through with no context and no summary line

Parameters:

Name Type Description Default
scope Scope

The ASGI connection scope

required
receive Receive

The ASGI receive channel, forwarded untouched

required
send Send

The ASGI send channel, wrapped to read the status

required

__init__(app)

Constructs an instance and binds the ASGI app to it

Parameters:

Name Type Description Default
app ASGIApp

The downstream ASGI application to wrap

required