oc_diagnostics.fastapi_middleware module#
FastAPI / ASGI Diagnostics Middleware#
Purpose#
Pure ASGI middleware that logs every HTTP request and response through
_dbg(), providing structured per-request diagnostics: HTTP method,
path, status code, client IP, and elapsed wall-clock time.
Responsibilities#
Implement
DiagnosticsMiddlewareas a pure ASGI callable that wraps any ASGI application without requiringstarlette.BaseHTTPMiddleware.Log request entry at L2 (method, path, client IP).
Log User-Agent header at L3 and all request/response headers at L4.
Capture HTTP status code from the
http.response.startASGI event via a lightweightsendwrapper; no request or response bodies are buffered.Measure and report wall-clock elapsed time in milliseconds.
Pass non-HTTP scopes (WebSocket, lifespan) through unchanged.
Log application-level exceptions at L2 before re-raising them.
Route all output through
_dbg()using the configurable domain (default:"HTTP").
Diagnostics#
Domain: HTTP Levels:
L2 — lifecycle (request start, response end, application errors) L3 — semantic details (User-Agent, 4xx/5xx status class) L4 — deep tracing (all request and response headers)
Contracts#
Must never suppress exceptions raised by the wrapped application; errors are logged at L2 and then re-raised unchanged.
Must not buffer or modify request or response bodies.
Must pass non-HTTP ASGI scopes (WebSocket, lifespan) through unchanged.
Does not require FastAPI at import time; works with any ASGI framework. Install the
[fastapi]optional extra for FastAPI framework utilities:pip install oc_diagnostics[fastapi]
The
HTTPdomain must be configured in the project’sdiagnostics/debug_config.jsonwith a non-zero level for log output to appear (DEBUG_LEVELS.get("HTTP", 0)defaults to disabled).
- class oc_diagnostics.fastapi_middleware.DiagnosticsMiddleware(app, domain: str = 'HTTP')[source]#
Bases:
objectPure ASGI middleware that logs HTTP requests and responses via
_dbg().- Parameters:
app (ASGI callable) – The next ASGI application in the middleware stack.
domain (str, optional) – Debug domain used for all log output. Defaults to
"HTTP". Must be configured indiagnostics/debug_config.jsonwith a non-zero level; unknown domains are silently filtered by_dbg().Usage
-----
registered:: (Add to a FastAPI application after all routes are) –
from fastapi import FastAPI from oc_diagnostics import DiagnosticsMiddleware
app = FastAPI() app.add_middleware(DiagnosticsMiddleware)
domain:: (With a custom) – app.add_middleware(DiagnosticsMiddleware, domain=”API”)
diagnostics/debug_config.json:: (Enable output by adding the HTTP domain to) – “HTTP”: { “level”: 2, “color”: “blue” }
middleware (Level guide for this) – L2 — request/response lifecycle lines (always recommended) L3 — User-Agent, 4xx/5xx status class commentary L4 — full request and response header dumps