INNER CODE UNIT · Python
request_logging_middleware
yaojingang/GEORank · backend/app/main.py:246
async def request_logging_middleware(request: Request, call_next):
"""输出请求结构化日志并附带 request_id。"""
request_id = uuid.uuid4().hex[:12]
started = time.perf_counter()
try:
response = await call_next(request)
except Exception:
duration_ms = round((time.perf_counter() - started) * 1000, 2)
log_event(
logger,
logging.ERROR,
"http.request.failed",
request_id=request_id,
method=request.method,
path=request.url.path,
query=str(request.url.query or ""),
duration_ms=duration_ms,
)