"""日志中间件:记录 RequestID/AgentID 链路与访问日志,避免敏感载荷与日志刷屏。""" import logging import time from starlette.middleware.base import BaseHTTPMiddleware from starlette.requests import Request logger = logging.getLogger("access") class RequestLogMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): start = time.perf_counter() # 心跳类接口降级为 debug,避免刷屏 is_heartbeat = request.url.path.endswith("/heartbeat") if logger.isEnabledFor(logging.DEBUG) or not is_heartbeat: logger.info( "%s %s path=%s", request.method, request.client.host if request.client else "-", request.url.path, ) response = await call_next(request) cost_ms = (time.perf_counter() - start) * 1000 if not is_heartbeat or logger.isEnabledFor(logging.DEBUG): logger.info( "%s %s -> %s (%dms)", request.method, request.url.path, response.status_code, round(cost_ms, 2), ) return response