Spaces:
Sleeping
Sleeping
File size: 891 Bytes
cd61bf7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | """Request ID middleware for tracing requests across logs."""
import uuid
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
import structlog
class RequestIDMiddleware(BaseHTTPMiddleware):
"""Add unique request ID to each request for tracing."""
async def dispatch(self, request: Request, call_next):
# Get or generate request ID
request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
# Add to structlog context
structlog.contextvars.bind_contextvars(request_id=request_id)
# Process request
response = await call_next(request)
# Add request ID to response headers
response.headers["X-Request-ID"] = request_id
# Clear context
structlog.contextvars.clear_contextvars()
return response
|