INNER CODE UNIT · Python
log_http_request
Earth-OL-Player/ai_learn_project · ai-service/app/main.py:22
async def log_http_request(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
"""记录进入 Python AI 服务的 HTTP 请求,便于判断前端链路是否打到本服务。"""
start_time = time.perf_counter()
trace_id = request.headers.get("x-trace-id", "")
# 请求进入时先打日志,避免鉴权失败或异常时看不到链路。
logger.info("收到 Python AI 服务请求:traceId=%s method=%s path=%s client=%s", trace_id, request.method, request.url.path, request.client.host if request.client else "")
response = await call_next(request)
# 请求结束时输出状态码和耗时,辅助定位是否被鉴权、路由或业务逻辑拦截。
duration_ms = elapsed_milliseconds(start_time)
if trace_id:
response.headers["X-Trace-Id"] = trace_id
logger.info("Python AI 服务请求完成:traceId=%s method=%s path=%s status=%s durationMs=%s", trace_id, request.method, request.url.path, response.status_code, duration_ms)
return response
@app.exception_handler(RequestValidationError)