| """ |
| Small helpers for benchmark-time API call logging and context propagation. |
| """ |
| from __future__ import annotations |
|
|
| from contextlib import contextmanager |
| from contextvars import ContextVar |
| from datetime import datetime, timezone |
| import json |
| from pathlib import Path |
| import threading |
| from typing import Any, Dict, Iterator, Optional |
|
|
|
|
| _CALL_CONTEXT: ContextVar[Dict[str, Any]] = ContextVar("simplemem_call_context", default={}) |
| _ACTIVE_LOGGER: "JsonlCallLogger | None" = None |
|
|
|
|
| def now_iso() -> str: |
| return datetime.now(timezone.utc).isoformat(timespec="seconds") |
|
|
|
|
| def current_call_context() -> Dict[str, Any]: |
| return dict(_CALL_CONTEXT.get()) |
|
|
|
|
| @contextmanager |
| def scoped_call_context(**updates: Any) -> Iterator[Dict[str, Any]]: |
| base = current_call_context() |
| merged = dict(base) |
| for key, value in updates.items(): |
| if value is not None: |
| merged[key] = value |
| token = _CALL_CONTEXT.set(merged) |
| try: |
| yield merged |
| finally: |
| _CALL_CONTEXT.reset(token) |
|
|
|
|
| class JsonlCallLogger: |
| def __init__(self, path: str | Path): |
| self.path = Path(path) |
| self.path.parent.mkdir(parents=True, exist_ok=True) |
| self._lock = threading.Lock() |
|
|
| def log(self, record: Dict[str, Any]) -> None: |
| payload = dict(record) |
| payload.setdefault("logged_at", now_iso()) |
| line = json.dumps(payload, ensure_ascii=False, sort_keys=True) |
| with self._lock: |
| with self.path.open("a", encoding="utf-8") as handle: |
| handle.write(line) |
| handle.write("\n") |
|
|
|
|
| def set_api_call_logger(logger: Optional[JsonlCallLogger]) -> None: |
| global _ACTIVE_LOGGER |
| _ACTIVE_LOGGER = logger |
|
|
|
|
| def get_api_call_logger() -> Optional[JsonlCallLogger]: |
| return _ACTIVE_LOGGER |
|
|
|
|
| def log_api_call(record: Dict[str, Any]) -> None: |
| logger = get_api_call_logger() |
| if logger is not None: |
| logger.log(record) |
|
|