1
from flask import request, Response
2
from prometheus_client import generate_latest, Counter, Histogram, Gauge, CONTENT_TYPE_LATEST
5
REQUEST_COUNT = Counter(
15
REQUEST_LATENCY = Histogram("http_request_latency_seconds", "Request latency", ["endpoint"])
17
REQUEST_IN_PROGRESS = Gauge(
18
"http_request_in_progress",
19
"Requests in progress",
26
def do_not_track(func):
27
func._do_not_track = True
31
def setup_metrics(app):
33
@app.route("/ready", methods=["GET"])
39
@app.route("/health", methods=["GET"])
45
@app.route("/metrics", methods=["GET"])
48
return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)
50
def ignore_endpoint():
51
view_func = app.view_functions.get(request.endpoint)
52
return hasattr(view_func, "_do_not_track")
57
request.start_time = time.time()
58
REQUEST_IN_PROGRESS.labels(request.path).inc()
60
def after_request(response):
63
resp_time = time.time() - request.start_time
64
REQUEST_COUNT.labels(request.method, request.path, response.status_code).inc()
65
REQUEST_LATENCY.labels(request.path).observe(resp_time)
66
REQUEST_IN_PROGRESS.labels(request.path).dec()
69
app.before_request(before_request)
70
app.after_request(after_request)