ADK-gateway/backend/app/middleware.py
2026-08-04 17:20:08 +08:00

33 lines
1.2 KiB
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.

"""日志中间件:记录 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