Prometheus Metrics Exporter for Starlette

0.23.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

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.

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

view raw JSON →