업데이트
This commit is contained in:
40
src/metrics.py
Normal file
40
src/metrics.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# src/metrics.py
|
||||
"""Lightweight metrics collection: counters and timers to JSON file."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .common import LOG_DIR
|
||||
|
||||
METRICS_FILE = os.path.join(LOG_DIR, "metrics.json")
|
||||
|
||||
|
||||
class Metrics:
|
||||
def __init__(self) -> None:
|
||||
self._counters: dict[str, int] = {}
|
||||
self._timers: dict[str, float] = {}
|
||||
|
||||
def inc(self, key: str, n: int = 1) -> None:
|
||||
self._counters[key] = self._counters.get(key, 0) + n
|
||||
|
||||
def observe(self, key: str, value: float) -> None:
|
||||
# Store last observed value
|
||||
self._timers[key] = float(value)
|
||||
|
||||
def dump(self) -> None:
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
payload = {
|
||||
"ts": time.time(),
|
||||
"counters": self._counters,
|
||||
"timers": self._timers,
|
||||
}
|
||||
try:
|
||||
with open(METRICS_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, ensure_ascii=False, indent=2)
|
||||
except Exception:
|
||||
# Metrics should never crash app
|
||||
pass
|
||||
|
||||
|
||||
metrics = Metrics()
|
||||
Reference in New Issue
Block a user