41 lines
973 B
Python
41 lines
973 B
Python
# src/web/api/routers/events.py
|
|
from fastapi import APIRouter, Query
|
|
from pathlib import Path
|
|
from collections import deque
|
|
|
|
router = APIRouter(prefix="/events", tags=["events"])
|
|
|
|
|
|
def _tail_file(path: Path, n: int) -> list[str]:
|
|
if not path.exists():
|
|
return []
|
|
dq = deque(maxlen=n)
|
|
with path.open("r", encoding="utf-8", errors="ignore") as f:
|
|
for line in f:
|
|
dq.append(line.rstrip())
|
|
return list(dq)
|
|
|
|
|
|
@router.get("")
|
|
def events(
|
|
limit: int = Query(200, ge=1, le=2000),
|
|
kind: str = Query("trading", pattern="^(trading|errors)$"),
|
|
):
|
|
logs_dir = Path("logs")
|
|
pattern = "trading_bot_*.log" if kind == "trading" else "errors_*.log"
|
|
|
|
files = sorted(
|
|
logs_dir.glob(pattern),
|
|
key=lambda p: p.stat().st_mtime,
|
|
reverse=True,
|
|
)
|
|
|
|
if not files:
|
|
return {"items": []}
|
|
|
|
lines = _tail_file(files[0], limit)
|
|
return {
|
|
"items": lines,
|
|
"file": files[0].name,
|
|
}
|