Spaces:
Build error
Build error
Create utils/monitoring.py
Browse files- utils/monitoring.py +46 -0
utils/monitoring.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from prometheus_client import Counter, Histogram, start_http_server
|
| 3 |
+
from functools import wraps
|
| 4 |
+
import time
|
| 5 |
+
from typing import Callable, Any
|
| 6 |
+
|
| 7 |
+
class MetricsManager:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
self.requests_total = Counter(
|
| 10 |
+
'requests_total',
|
| 11 |
+
'Total requests processed',
|
| 12 |
+
['endpoint']
|
| 13 |
+
)
|
| 14 |
+
self.request_duration = Histogram(
|
| 15 |
+
'request_duration_seconds',
|
| 16 |
+
'Request duration in seconds',
|
| 17 |
+
['endpoint']
|
| 18 |
+
)
|
| 19 |
+
self.errors_total = Counter(
|
| 20 |
+
'errors_total',
|
| 21 |
+
'Total errors encountered',
|
| 22 |
+
['type']
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# Start Prometheus metrics server
|
| 26 |
+
start_http_server(8000)
|
| 27 |
+
|
| 28 |
+
def monitor_performance(endpoint: str) -> Callable:
|
| 29 |
+
def decorator(func: Callable) -> Callable:
|
| 30 |
+
@wraps(func)
|
| 31 |
+
def wrapper(*args, **kwargs) -> Any:
|
| 32 |
+
start_time = time.time()
|
| 33 |
+
try:
|
| 34 |
+
result = func(*args, **kwargs)
|
| 35 |
+
metrics_manager.requests_total.labels(endpoint=endpoint).inc()
|
| 36 |
+
return result
|
| 37 |
+
except Exception as e:
|
| 38 |
+
metrics_manager.errors_total.labels(type=type(e).__name__).inc()
|
| 39 |
+
raise
|
| 40 |
+
finally:
|
| 41 |
+
duration = time.time() - start_time
|
| 42 |
+
metrics_manager.request_duration.labels(endpoint=endpoint).observe(duration)
|
| 43 |
+
return wrapper
|
| 44 |
+
return decorator
|
| 45 |
+
|
| 46 |
+
metrics_manager = MetricsManager()
|