"""请求日志查询接口""" from fastapi import APIRouter from app.middleware import get_request_log, clear_request_log router = APIRouter(tags=["logs"]) @router.get("/api/v1/logs") async def list_logs( limit: int = 100, path: str = None, method: str = None, status: int = None, ): """ 获取请求日志(最近 N 条) - limit: 返回条数(默认100,最大500) - path: 路径过滤(支持模糊) - method: 方法过滤(GET/POST) - status: 状态码过滤 """ logs = get_request_log() if limit and 0 < limit <= 500: logs = logs[:limit] if path: logs = [l for l in logs if path.lower() in l.get("path", "").lower()] if method: logs = [l for l in logs if l.get("method", "").upper() == method.upper()] if status: logs = [l for l in logs if l.get("status") == status] return {"total": len(get_request_log()), "count": len(logs), "logs": logs} @router.post("/api/v1/logs/clear") async def clear_logs(): """清空请求日志""" n = clear_request_log() return {"cleared": n}