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.
pip install starlette-exporterVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to set up `starlette-exporter` with a basic Starlette application. It defines two simple routes and exposes a `/metrics` endpoint using `handle_metrics`. The `PrometheusMiddleware` is added to the application, configuring it to group paths for cleaner metrics. To run, save the code, install dependencies, and execute with uvicorn.
If your application relied on the previous behavior without explicitly setting these options, you must now explicitly set `group_paths=False` or `filter_unhandled_paths=False` in the `PrometheusMiddleware` constructor to revert to the old defaults.
Ensure your project uses Starlette 0.35.0 or newer and Python 3.8 or newer. Upgrade your environment and dependencies accordingly.
Review existing `skip_paths` configurations. If you intended exact string matches, ensure they are properly escaped (e.g., `['/my/path/']` might need `['/my/path/?']` if `?` was previously treated as a literal but is now a regex special character).
Update any monitoring alerts or dashboards that specifically look for `500` status codes for client disconnections to include `499`.
To get metrics for requests against unhandled paths, set `group_unhandled_paths=True` in the `PrometheusMiddleware` constructor. This option overrides `filter_unhandled_paths`.
pip install starlette-exporter
pip install fastapi==0.89.1 starlette==0.22.0
Upgrade `starlette-exporter` to version `0.23.0` or newer. If upgrading is not immediately possible, disable path grouping by initializing the middleware with `group_paths=False`: `app.add_middleware(PrometheusMiddleware, group_paths=False)`.
Ensure both the `PrometheusMiddleware` is added to your Starlette application AND `handle_metrics` is registered as a route: `app.add_middleware(PrometheusMiddleware)` and `app.add_route('/metrics', handle_metrics)`. Additionally, verify that your Prometheus configuration includes a scrape job targeting your application's `/metrics` endpoint.The middleware is functioning as designed by measuring the duration until the response. If you need to monitor the duration of background tasks, you should instrument those tasks separately using custom Prometheus metrics (e.g., `prometheus_client.Histogram`) within the background task's logic.