Prometheus Metrics Exporter for Starlette
starlette-exporter is a Python library that provides Prometheus metrics for Starlette applications, enabling easy monitoring of request rates, durations, and response statuses. It integrates as a middleware, automatically exposing a `/metrics` endpoint. The current version is 0.23.0, and it follows a regular release cadence with new features and improvements.
Warnings
- breaking The default values for `group_paths` and `filter_unhandled_paths` changed from `False` to `True`.
- breaking Minimum supported Starlette version increased to 0.35, and Python 3.7 support was dropped.
- gotcha The `skip_paths` option now accepts regular expressions, which can subtly change behavior if existing exact path strings were coincidentally valid regex patterns.
- gotcha Client disconnections (before a response is sent) are now reported with status code `499` instead of `500`.
- gotcha Unhandled paths (404s) can now be grouped under a special `__unknown__` label, but this feature requires explicit enablement.
Install
-
pip install starlette-exporter
Imports
- PrometheusMiddleware
from starlette_exporter import PrometheusMiddleware
- handle_metrics
from starlette_exporter import handle_metrics
- from_header
from starlette_exporter import from_header
- from_response_header
from starlette_exporter import from_response_header
Quickstart
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.routing import Route
from starlette_exporter import PrometheusMiddleware, handle_metrics
import uvicorn
async def homepage(request):
return PlainTextResponse("Hello, world!")
async def user_page(request):
username = request.path_params.get("username")
return PlainTextResponse(f"Hello, {username}!")
routes = [
Route("/", homepage),
Route("/users/{username}", user_page),
Route("/metrics", handle_metrics) # Expose the metrics endpoint
]
app = Starlette(routes=routes)
app.add_middleware(
PrometheusMiddleware,
app_name="my_starlette_app",
group_paths=True, # Recommended for clean metrics paths
# labels={"environment": "staging"}, # Example custom labels
# group_unhandled_paths=True # New in v0.23.0 to group 404s under '__unknown__'
)
# To run this application:
# 1. Save the code as `main.py`
# 2. Install dependencies: `pip install uvicorn starlette starlette-exporter prometheus_client`
# 3. Run: `uvicorn main:app --reload`
# Then, access metrics at http://127.0.0.1:8000/metrics
# And application routes at http://127.0.0.1:8000/ or http://127.0.0.1:8000/users/alice