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

1"""Lightweight JSONL metrics helpers.""" 

2 

3from __future__ import annotations 

4 

5import json 

6import time 

7from pathlib import Path 

8from typing import Any, Union 

9 

10PathLike = Union[str, "Path"] 

11 

12 

13def _ensure_dir(path: Path) -> None: 

14 """Create the parent directory for ``path`` if it is missing.""" 

15 

16 parent = path.parent 

17 if parent != Path(""): 

18 parent.mkdir(parents=True, exist_ok=True) 

19 

20 

21def log_event(event_type: str, path: PathLike, **fields: Any) -> None: 

22 """Append a structured metrics record to ``path``. 

23 

24 The file is encoded as UTF-8 JSONL so that it can easily be tailed or 

25 ingested by lightweight tooling. 

26 """ 

27 

28 target = Path(path) 

29 _ensure_dir(target) 

30 

31 record = {"ts": int(time.time() * 1000), "event": event_type} 

32 record.update(fields) 

33 

34 with target.open("a", encoding="utf-8") as handle: 

35 handle.write(json.dumps(record, ensure_ascii=False) + "\n")