Coverage for projects/04-llm-adapter-shadow/src/llm_adapter/metrics.py: 100%
17 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-24 01:32 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-09-24 01:32 +0000
1"""Lightweight JSONL metrics helpers."""
3from __future__ import annotations
5import json
6import time
7from pathlib import Path
8from typing import Any, Union
10PathLike = Union[str, "Path"]
13def _ensure_dir(path: Path) -> None:
14 """Create the parent directory for ``path`` if it is missing."""
16 parent = path.parent
17 if parent != Path(""):
18 parent.mkdir(parents=True, exist_ok=True)
21def log_event(event_type: str, path: PathLike, **fields: Any) -> None:
22 """Append a structured metrics record to ``path``.
24 The file is encoded as UTF-8 JSONL so that it can easily be tailed or
25 ingested by lightweight tooling.
26 """
28 target = Path(path)
29 _ensure_dir(target)
31 record = {"ts": int(time.time() * 1000), "event": event_type}
32 record.update(fields)
34 with target.open("a", encoding="utf-8") as handle:
35 handle.write(json.dumps(record, ensure_ascii=False) + "\n")