Initial commit
This commit is contained in:
46
backend/app/middleware/correlation_id.py
Normal file
46
backend/app/middleware/correlation_id.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
Correlation ID Middleware - ServiceManagerWeb
|
||||
|
||||
Middleware para rastrear requests con correlation ID
|
||||
"""
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.responses import Response
|
||||
import uuid
|
||||
import structlog
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
class CorrelationIDMiddleware(BaseHTTPMiddleware):
|
||||
"""
|
||||
Middleware para manejar correlation IDs.
|
||||
|
||||
Extrae el correlation ID del header X-Correlation-ID o genera uno nuevo.
|
||||
Lo almacena en el estado de la request para uso en logs y responses.
|
||||
"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next) -> Response:
|
||||
"""Process request and add correlation ID."""
|
||||
|
||||
# Extract or generate correlation ID
|
||||
correlation_id = request.headers.get("X-Correlation-ID")
|
||||
if not correlation_id:
|
||||
correlation_id = str(uuid.uuid4())
|
||||
|
||||
# Store in request state
|
||||
request.state.correlation_id = correlation_id
|
||||
|
||||
# Add to structlog context
|
||||
with structlog.contextvars.bound_contextvars(
|
||||
correlation_id=correlation_id,
|
||||
path=request.url.path,
|
||||
method=request.method
|
||||
):
|
||||
response = await call_next(request)
|
||||
|
||||
# Add correlation ID to response headers
|
||||
response.headers["X-Correlation-ID"] = correlation_id
|
||||
|
||||
return response
|
||||
Reference in New Issue
Block a user