Skip to content

Instantly share code, notes, and snippets.

@nda86
Created May 11, 2025 10:09
Show Gist options
  • Save nda86/a02125a4d5da00c6412f5f3023c17af9 to your computer and use it in GitHub Desktop.
Save nda86/a02125a4d5da00c6412f5f3023c17af9 to your computer and use it in GitHub Desktop.
vtnhbrb
from typing import Callable
from prometheus_client import Counter, Histogram, generate_latest
from time import time
from flask import request, Response
REQUEST_COUNT = Counter(
"http_requests_total",
"Total HTTP requests",
["method", "endpoint", "http_status"],
)
REQUEST_LATENCY = Histogram(
"http_request_duration_seconds",
"HTTP request latency in seconds",
["method", "endpoint", "http_status"],
)
METRICS_LABELS = {}
ENDPOINT_MATCHER: list[tuple[Callable[[str], bool], str]] = [
(lambda s: s.startswith("/api/v1/dashboard/"), "dashboard"),
(lambda s: s.startswith("/api/v1/chart/"), "chart"),
(lambda s: s.startswith("/api/v1/slice/"), "slice"),
(lambda s: "/explore/" in s, "explore"),
]
def get_metric_label(rule):
for matcher, label in ENDPOINT_MATCHER:
if matcher(rule):
return label
return None
class MetricsMiddleware:
def __init__(self, app):
self.app = app
@self.app.route("/metrics")
def metrics():
return Response(generate_latest(), mimetype="text/plain")
@self.app.before_request
def start_timer():
request._start_time = time()
@self.app.after_request
def record_metrics(response):
start = getattr(request, "_start_time", None)
rule_obj = getattr(request, "url_rule", None)
label = get_metric_label(rule_obj.rule)
if start and label:
latency = time() - start
REQUEST_LATENCY.labels(request.method, label, str(response.status_code)).observe(latency)
REQUEST_COUNT.labels(request.method, label, str(response.status_code)).inc()
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment