""" 审计日志 API ============ 【功能说明】 提供审计日志的查询接口,支撑前端「审计可视化」页面。 对应 M5 交付目标:Agent 的每次动手操作可追溯、可审查。 【技术选型理由】 1. 只读接口:审计日志是证据,绝不允许通过 API 修改/删除; 2. 按日期分文件的 JSONL 直接读取并过滤,无需额外数据库; 3. 支持按 action/result 过滤 + 分页,满足审查场景。 【实现思路】 - GET /api/audit:读取当日(或指定日期)审计日志并过滤; - 结构化返回,前端表格展示。 【潜在风险与应对】 风险1:日志文件过大读取慢。 应对:limit 上限 500 条,倒序返回最近的。 """ from __future__ import annotations import json import logging from datetime import datetime from pathlib import Path from typing import Any from fastapi import APIRouter, Query from app.schemas.project import ApiResponse logger = logging.getLogger("agent.audit.api") router = APIRouter(prefix="/api/audit", tags=["审计日志"]) AUDIT_DIR = Path(r"D:\Agent\agent\data\audit") @router.get("", response_model=ApiResponse[list[dict[str, Any]]], summary="查询审计日志") def list_audit_logs( date: str = Query(default="", description="日期 YYYYMMDD,默认今日"), action: str = Query(default="", description="操作类型过滤"), limit: int = Query(default=100, ge=1, le=500, description="返回条数上限"), ) -> ApiResponse[list[dict[str, Any]]]: """ 查询审计日志(支持按日期/操作类型过滤)。 【返回】最近 N 条审计记录,倒序(最新的在前)。 """ date_str = date or datetime.now().strftime("%Y%m%d") log_file = AUDIT_DIR / f"audit-{date_str}.jsonl" if not log_file.exists(): return ApiResponse( code=0, message=f"日期 {date_str} 无审计记录", data=[], ) entries: list[dict[str, Any]] = [] try: with open(log_file, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: entry = json.loads(line) except json.JSONDecodeError: continue if action and entry.get("action") != action: continue entries.append(entry) except Exception as exc: return ApiResponse(code=500, message=f"读取审计日志失败:{exc}", data=None) # 倒序取最近 N 条 entries.reverse() entries = entries[:limit] return ApiResponse( code=0, message=f"共 {len(entries)} 条记录", data=entries, ) @router.get("/summary", response_model=ApiResponse[dict[str, Any]], summary="审计统计") def audit_summary( date: str = Query(default="", description="日期 YYYYMMDD,默认今日"), ) -> ApiResponse[dict[str, Any]]: """返回当日审计操作的统计概览(按 action/result 分组计数)。""" date_str = date or datetime.now().strftime("%Y%m%d") log_file = AUDIT_DIR / f"audit-{date_str}.jsonl" if not log_file.exists(): return ApiResponse(code=0, message="ok", data={"total": 0, "by_action": {}, "by_result": {}}) by_action: dict[str, int] = {} by_result: dict[str, int] = {} total = 0 try: with open(log_file, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: entry = json.loads(line) except json.JSONDecodeError: continue total += 1 action = entry.get("action", "unknown") result = entry.get("result", "unknown") by_action[action] = by_action.get(action, 0) + 1 by_result[result] = by_result.get(result, 0) + 1 except Exception as exc: return ApiResponse(code=500, message=f"统计失败:{exc}", data=None) return ApiResponse( code=0, message="ok", data={"total": total, "by_action": by_action, "by_result": by_result}, )