76 lines
2.3 KiB
Python
76 lines
2.3 KiB
Python
"""
|
||||
|
|
日志聚合 API
|
|||
|
|
============
|
|||
|
|
|
|||
|
|
【功能说明】本地日志查询 + 推送到外部日志系统(预留 Webhook)。
|
|||
|
|
对应功能 35:日志聚合。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import logging
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
from fastapi import APIRouter, Query
|
|||
|
|
|
|||
|
|
from app.schemas.project import ApiResponse
|
|||
|
|
|
|||
|
|
logger = logging.getLogger("agent.log_aggregation.api")
|
|||
|
|
|
|||
|
|
router = APIRouter(prefix="/api/logs", tags=["日志聚合"])
|
|||
|
|
|
|||
|
|
# 审计日志目录
|
|||
|
|
AUDIT_DIR = Path(r"D:\Agent\agent\data\audit")
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.get("", response_model=ApiResponse[dict], summary="查询日志")
|
|||
|
|
def query_logs(
|
|||
|
|
keyword: str = Query(default="", description="关键字过滤"),
|
|||
|
|
limit: int = Query(default=100, ge=1, le=500),
|
|||
|
|
) -> ApiResponse[dict]:
|
|||
|
|
"""查询审计日志(支持关键字过滤)。"""
|
|||
|
|
import json
|
|||
|
|
|
|||
|
|
logs = []
|
|||
|
|
for f in sorted(AUDIT_DIR.glob("audit-*.jsonl"), reverse=True)[:7]:
|
|||
|
|
try:
|
|||
|
|
with open(f, encoding="utf-8") as fp:
|
|||
|
|
for line in fp:
|
|||
|
|
if not line.strip():
|
|||
|
|
continue
|
|||
|
|
entry = json.loads(line)
|
|||
|
|
if keyword and keyword.lower() not in str(entry).lower():
|
|||
|
|
continue
|
|||
|
|
logs.append(entry)
|
|||
|
|
except Exception: # noqa: BLE001
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
logs.reverse()
|
|||
|
|
logs = logs[:limit]
|
|||
|
|
return ApiResponse(code=0, message=f"共 {len(logs)} 条", data={"logs": logs})
|
|||
|
|
|
|||
|
|
|
|||
|
|
@router.post("/push", response_model=ApiResponse[dict], summary="推送日志到外部系统")
|
|||
|
|
def push_logs(payload: dict) -> ApiResponse[dict]:
|
|||
|
|
"""
|
|||
|
|
推送日志到外部日志系统(Webhook/ELK/Loki 预留接口)。
|
|||
|
|
|
|||
|
|
【请求体】{"target": "webhook_url", "logs": [...]}
|
|||
|
|
"""
|
|||
|
|
target = payload.get("target", "")
|
|||
|
|
logs = payload.get("logs", [])
|
|||
|
|
if not target:
|
|||
|
|
return ApiResponse(code=422, message="target(Webhook URL)必填", data=None)
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
import httpx
|
|||
|
|
|
|||
|
|
resp = httpx.post(target, json={"logs": logs}, timeout=10.0)
|
|||
|
|
return ApiResponse(
|
|||
|
|
code=0 if resp.status_code < 400 else 1,
|
|||
|
|
message=f"推送完成(HTTP {resp.status_code})",
|
|||
|
|
data={"status_code": resp.status_code},
|
|||
|
|
)
|
|||
|
|
except Exception as exc: # noqa: BLE001
|
|||
|
|
return ApiResponse(code=1, message=f"推送失败:{exc}", data=None)
|