from __future__ import annotations import logging import time from uuid import uuid4 from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request from app.core.config import settings logger = logging.getLogger("vent_platform.http") class RequestContextMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): trace_id = request.headers.get(settings.request_trace_header) or uuid4().hex request.state.trace_id = trace_id started = time.perf_counter() response = await call_next(request) response.headers[settings.request_trace_header] = trace_id logger.info( "%s %s status=%s duration_ms=%.1f trace_id=%s", request.method, request.url.path, response.status_code, (time.perf_counter() - started) * 1000, trace_id, ) return response