Starlette Prometheus Integration

0.10.0 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import uvicorn
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette_prometheus import PrometheusMiddleware, metrics

app = Starlette()
app.add_middleware(PrometheusMiddleware, app_name='my_starlette_app', prefix='starlette_app_prefix')
app.add_route('/metrics', metrics)

@app.route('/')
async def homepage(request):
    return PlainTextResponse('Hello, world!')

@app.route('/items/{item_id}')
async def read_item(request):
    item_id = request.path_params['item_id']
    return PlainTextResponse(f'Item: {item_id}')

if __name__ == '__main__':
    # Run with: uvicorn quickstart:app --port 8000
    uvicorn.run(app, host='0.0.0.0', port=8000)

view raw JSON →