"""Prometheus 指标模块""" from prometheus_client import Counter, Histogram, Gauge, CollectorRegistry from functools import wraps import time from typing import Callable # 创建指标注册表 metrics_registry = CollectorRegistry() # 请求计数器 request_counter = Counter( "http_requests_total", "Total HTTP requests", ["method", "endpoint", "status"], registry=metrics_registry, ) # 请求延迟直方图 request_latency = Histogram( "http_request_duration_seconds", "HTTP request latency", ["method", "endpoint"], registry=metrics_registry, ) # 算法执行计数器 algorithm_counter = Counter( "algorithm_executions_total", "Total algorithm executions", ["algorithm", "status"], registry=metrics_registry, ) # 算法执行延迟 algorithm_latency = Histogram( "algorithm_execution_duration_seconds", "Algorithm execution latency", ["algorithm"], registry=metrics_registry, ) # 当前处理中的请求数 in_progress_requests = Gauge( "http_requests_in_progress", "Number of HTTP requests in progress", registry=metrics_registry, ) def track_request(method: str, endpoint: str): """ 装饰器:跟踪HTTP请求指标 Args: method: HTTP方法 endpoint: 端点路径 """ def decorator(func: Callable): @wraps(func) async def wrapper(*args, **kwargs): in_progress_requests.inc() start_time = time.time() try: result = await func(*args, **kwargs) status = "success" return result except Exception as e: status = "error" raise e finally: elapsed = time.time() - start_time request_counter.labels(method=method, endpoint=endpoint, status=status).inc() request_latency.labels(method=method, endpoint=endpoint).observe(elapsed) in_progress_requests.dec() return wrapper return decorator def track_algorithm_execution(algorithm_name: str): """ 装饰器:跟踪算法执行指标 Args: algorithm_name: 算法名称 """ def decorator(func: Callable): @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() try: result = func(*args, **kwargs) status = "success" return result except Exception as e: status = "error" raise e finally: elapsed = time.time() - start_time algorithm_counter.labels(algorithm=algorithm_name, status=status).inc() algorithm_latency.labels(algorithm=algorithm_name).observe(elapsed) return wrapper return decorator