2026-02-15 20:04:11 +02:00

55 lines
1.4 KiB
Python

import time
from prometheus_client import Counter, Histogram
HTTP_REQUESTS_TOTAL = Counter(
"http_requests_total",
"Total HTTP requests",
["endpoint", "method", "status"],
)
HTTP_REQUEST_DURATION_SECONDS = Histogram(
"http_request_duration_seconds",
"HTTP request duration in seconds",
["endpoint", "method"],
)
CACHE_HITS_TOTAL = Counter(
"coordinates_cache_hits_total",
"Total cache hits for coordinates",
)
CACHE_MISSES_TOTAL = Counter(
"coordinates_cache_misses_total",
"Total cache misses for coordinates",
)
OPENMETEO_CALLS_TOTAL = Counter(
"openmeteo_api_calls_total",
"Total calls made to Open-Meteo Geocoding API",
["city"],
)
class RequestTimer:
"""Small helper to measure request duration and emit metrics."""
def __init__(self, endpoint: str, method: str):
self.endpoint = endpoint
self.method = method
self.start = None
self.status = "200"
def __enter__(self):
self.start = time.time()
return self
def set_status(self, status: str):
self.status = status
def __exit__(self, exc_type, exc, tb):
HTTP_REQUESTS_TOTAL.labels(
endpoint=self.endpoint, method=self.method, status=self.status
).inc()
HTTP_REQUEST_DURATION_SECONDS.labels(
endpoint=self.endpoint, method=self.method
).observe(time.time() - self.start)