Files
blog-writer/dashboard/backend/api_logs.py
sinmb79 213f57b52d feat: v3.1 대시보드 추가 (React + FastAPI)
Media Engine Control Panel — 6탭 웹 대시보드

[백엔드] FastAPI (dashboard/backend/)
- server.py: 포트 8080, CORS, React SPA 서빙
- api_overview.py: KPI 카드 + 파이프라인 상태 + 활동 로그
- api_content.py: 칸반 보드 + 승인/거부 + 수동 트리거
- api_analytics.py: 방문자 추이 + 플랫폼/코너별 성과
- api_novels.py: 소설 목록/생성/에피소드 관리
- api_settings.py: engine.json CRUD
- api_connections.py: AI 서비스 연결 관리 + 키 저장
- api_tools.py: 기능별 AI 도구 선택
- api_cost.py: 구독 현황 + API 사용량 추적
- api_logs.py: 시스템 로그 필터/검색

[프론트엔드] React + Vite + Tailwind + Recharts (dashboard/frontend/)
- Overview: KPI 카드 + 파이프라인 + 코너별 바차트 + 활동 로그
- Content: 4열 칸반 보드 + 상세 모달 + 승인/거부
- Analytics: LineChart 방문자 추이 + 플랫폼별 성과
- Novel: 소설 목록 + 에피소드 테이블 + 새 소설 생성 폼
- Settings: 5개 서브탭 (AI연결/도구선택/배포채널/품질/비용관리)
- Logs: 필터/검색 시스템 로그 뷰어

[디자인] CNN 다크+골드 테마
- 배경 #0a0a0d + 액센트 #c8a84e
- 모바일 반응형 (Tailscale 외부 접속 대응)

[실행]
- dashboard/start.bat 더블클릭 → http://localhost:8080

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 13:17:53 +09:00

110 lines
2.8 KiB
Python

"""
dashboard/backend/api_logs.py
Logs 탭 API — 시스템 로그 파싱, 필터/검색
"""
import re
from pathlib import Path
from typing import Optional
from fastapi import APIRouter, Query
BASE_DIR = Path(__file__).parent.parent.parent
LOGS_DIR = BASE_DIR / "logs"
router = APIRouter()
LOG_MODULES = {
"": "전체",
"scheduler": "스케줄러",
"collector": "수집",
"writer": "글쓰기",
"converter": "변환",
"publisher": "발행",
"analytics": "분석",
"novel": "소설",
"engine_loader": "엔진",
"error": "에러만",
}
LOG_PATTERN = re.compile(
r"(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})[,\.]?\d*\s+"
r"\[?(\w+)\]?\s+(.*)"
)
def _parse_log_line(line: str, module: str) -> dict | None:
m = LOG_PATTERN.match(line.strip())
if not m:
return None
return {
"time": m.group(1),
"level": m.group(2).upper(),
"module": module,
"message": m.group(3)[:300],
}
def _read_logs(
filter_module: str = "",
search: str = "",
limit: int = 200,
) -> list:
logs = []
if not LOGS_DIR.exists():
return logs
# 로그 파일 목록 (최근 수정 순)
log_files = sorted(LOGS_DIR.glob("*.log"), key=lambda f: f.stat().st_mtime, reverse=True)
error_only = filter_module == "error"
for log_file in log_files:
module_name = log_file.stem # e.g. "scheduler", "collector"
# 모듈 필터
if filter_module and not error_only and module_name != filter_module:
continue
try:
lines = log_file.read_text(encoding="utf-8", errors="ignore").splitlines()
for line in reversed(lines):
if not line.strip():
continue
entry = _parse_log_line(line, module_name)
if entry is None:
continue
# 에러만 필터
if error_only and entry["level"] not in ("ERROR", "CRITICAL", "WARNING"):
continue
# 검색 필터
if search and search.lower() not in entry["message"].lower():
continue
logs.append(entry)
if len(logs) >= limit:
break
except Exception:
pass
if len(logs) >= limit:
break
return logs[:limit]
@router.get("/logs")
async def get_logs(
filter: str = Query(default="", description="모듈 필터 (scheduler/collector/writer/converter/publisher/error)"),
search: str = Query(default="", description="메시지 검색"),
limit: int = Query(default=200, ge=1, le=1000),
):
logs = _read_logs(filter_module=filter, search=search, limit=limit)
return {
"logs": logs,
"total": len(logs),
"modules": LOG_MODULES,
}