import os from fastapi import APIRouter, Depends, HTTPException, Query from ..dependencies import require_admin from ..models.user import User from ..config import get_settings router = APIRouter(prefix="/api/logs", tags=["logs"]) _LOG_FILES = { "app": "app.log", "matching": "matching.log", } @router.get("/{log_name}") async def get_log( log_name: str, lines: int = Query(300, ge=10, le=5000), _admin: User = Depends(require_admin), ): if log_name not in _LOG_FILES: raise HTTPException(status_code=404, detail="Unbekannte Log-Datei") settings = get_settings() path = os.path.join(settings.log_dir, _LOG_FILES[log_name]) if not os.path.exists(path): return {"lines": [], "total": 0, "showing": 0, "exists": False, "path": path} with open(path, "r", encoding="utf-8", errors="replace") as f: all_lines = f.readlines() last = all_lines[-lines:] return { "lines": [l.rstrip("\n") for l in last], "total": len(all_lines), "showing": len(last), "exists": True, "path": path, } @router.delete("/{log_name}") async def clear_log( log_name: str, _admin: User = Depends(require_admin), ): if log_name not in _LOG_FILES: raise HTTPException(status_code=404, detail="Unbekannte Log-Datei") settings = get_settings() path = os.path.join(settings.log_dir, _LOG_FILES[log_name]) if os.path.exists(path): open(path, "w").close() return {"success": True}