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.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat are pytest fixtures, and what scopes exist?IntermediateWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?Beginner