File size: 1,928 Bytes
a54fd97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
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)