Interview Prep/Python for DevOps/Testing, services & metrics

How do you instrument a Python service with Prometheus metrics?

IntermediateConceptTesting, services & metrics
Answer
from prometheus_client import Counter, Histogram, start_http_server

REQS = Counter("webhook_requests_total", "Webhook requests", ["event", "status"])
LAT = Histogram("webhook_duration_seconds", "Handler latency",
                buckets=(0.05, 0.1, 0.25, 0.5, 1, 2.5, 5))

@LAT.time()
def handle(event):
    ...
    REQS.labels(event=event, status="ok").inc()

start_http_server(9100)   # serves /metrics on a separate port

With Flask you can mount prometheus_client.make_wsgi_app() at /metrics; with FastAPI, make_asgi_app(). Naming: snake_case, base units (seconds, bytes), _total suffix on counters.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics