Files
life-echo/api/app/core/middleware.py

24 lines
694 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
HTTP 中间件request_id 注入。
"""
import uuid
from loguru import logger
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
class RequestIdMiddleware(BaseHTTPMiddleware):
"""Inject request_id into request.state and response headers, bind to loguru context."""
async def dispatch(self, request: Request, call_next):
request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
request.state.request_id = request_id
with logger.contextualize(request_id=request_id):
response = await call_next(request)
response.headers["X-Request-ID"] = request_id
return response