Starlette-prometheus is a Python library that provides seamless Prometheus integration for Starlette applications. It includes a middleware to automatically expose key metrics such as total requests, request duration, and concurrent requests. The library is currently at version 0.10.0, released on September 3, 2024, with a development cadence that includes periodic updates and feature enhancements.
pip install starlette-prometheus uvicornVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate `starlette-prometheus` into a basic Starlette application. It sets up `PrometheusMiddleware` to automatically collect HTTP request metrics and exposes them at the `/metrics` endpoint. Run this file using `uvicorn quickstart:app --port 8000` and then access `http://localhost:8000/metrics` to see the collected metrics.
Initialize PrometheusMiddleware with `filter_unhandled_paths=True`. Example: `app.add_middleware(PrometheusMiddleware, filter_unhandled_paths=True)`.
Set the `PROMETHEUS_MULTIPROC_DIR` environment variable to a shared directory. `prometheus_client` will use this directory to store metric files, which Prometheus can then scrape and aggregate. For example: `export PROMETHEUS_MULTIPROC_DIR=/tmp/prometheus_metrics`.
Upgrade `starlette-prometheus` to version `0.9.0` or higher to resolve the `UnboundLocalError: local variable 'status_code' referenced before assignment` bug.