|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import traceback |
| 5 | +from collections import Counter |
| 6 | +from datetime import datetime, timezone |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any |
| 9 | + |
| 10 | + |
| 11 | +DEFAULT_LOG_PATH = Path(__file__).resolve().parent / "logs" / "error-logs.jsonl" |
| 12 | + |
| 13 | + |
| 14 | +def _ensure_log_path(log_path: str | Path | None) -> Path: |
| 15 | + path = Path(log_path) if log_path is not None else DEFAULT_LOG_PATH |
| 16 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 17 | + return path |
| 18 | + |
| 19 | + |
| 20 | +def log_exception( |
| 21 | + project_name: str, |
| 22 | + exception: Exception, |
| 23 | + log_path: str | Path | None = None, |
| 24 | + additional_data: dict[str, Any] | None = None, |
| 25 | +) -> dict[str, Any]: |
| 26 | + """Write a structured exception entry to a JSON Lines log file.""" |
| 27 | + path = _ensure_log_path(log_path) |
| 28 | + payload = { |
| 29 | + "project_name": project_name, |
| 30 | + "exception_type": type(exception).__name__, |
| 31 | + "error_message": str(exception), |
| 32 | + "timestamp": datetime.now(timezone.utc).isoformat(), |
| 33 | + "traceback": "".join(traceback.format_exception(type(exception), exception, exception.__traceback__)), |
| 34 | + } |
| 35 | + |
| 36 | + if additional_data: |
| 37 | + payload["additional_data"] = additional_data |
| 38 | + |
| 39 | + with path.open("a", encoding="utf-8") as handle: |
| 40 | + handle.write(json.dumps(payload, ensure_ascii=False) + "\n") |
| 41 | + |
| 42 | + return payload |
| 43 | + |
| 44 | + |
| 45 | +def summarize_logs(log_path: str | Path | None = None) -> dict[str, Any]: |
| 46 | + """Return a compact summary of the stored error logs.""" |
| 47 | + path = _ensure_log_path(log_path) |
| 48 | + if not path.exists(): |
| 49 | + return { |
| 50 | + "total_errors": 0, |
| 51 | + "exception_counts": {}, |
| 52 | + "project_counts": {}, |
| 53 | + "latest_errors": [], |
| 54 | + } |
| 55 | + |
| 56 | + exception_counts: Counter[str] = Counter() |
| 57 | + project_counts: Counter[str] = Counter() |
| 58 | + latest_errors: list[dict[str, Any]] = [] |
| 59 | + |
| 60 | + with path.open("r", encoding="utf-8") as handle: |
| 61 | + for line in handle: |
| 62 | + line = line.strip() |
| 63 | + if not line: |
| 64 | + continue |
| 65 | + payload = json.loads(line) |
| 66 | + exception_counts[payload["exception_type"]] += 1 |
| 67 | + project_counts[payload["project_name"]] += 1 |
| 68 | + latest_errors.append(payload) |
| 69 | + |
| 70 | + return { |
| 71 | + "total_errors": sum(exception_counts.values()), |
| 72 | + "exception_counts": dict(exception_counts), |
| 73 | + "project_counts": dict(project_counts), |
| 74 | + "latest_errors": latest_errors[-5:], |
| 75 | + } |
| 76 | + |
| 77 | + |
| 78 | +def safe_run(project_name: str, action, log_path: str | Path | None = None): |
| 79 | + """Run an action while logging any unexpected exceptions.""" |
| 80 | + try: |
| 81 | + return action() |
| 82 | + except Exception as exc: # pylint: disable=broad-except |
| 83 | + log_exception(project_name, exc, log_path=log_path) |
| 84 | + raise |
0 commit comments