Prometheus FastAPI Instrumentator
This library provides a straightforward way to instrument your FastAPI or Starlette applications with Prometheus metrics. It automatically exposes common HTTP request metrics and allows for custom metric definitions. Currently at version 7.1.0, it maintains an active development pace with frequent updates and bug fixes, typically releasing minor versions every few months and major versions annually.
Warnings
- breaking Python 3.7 is no longer supported as of version 7.0.0. Applications running on Python 3.7 will fail.
- breaking Accessing `info.response.body` in custom instrumentation functions is disabled by default in version 6.0.0 due to performance and security concerns.
- deprecated The lowercase `prometheus_multiproc_dir` environment variable was deprecated in version 5.10.0.
- gotcha For reliable startup and to avoid potential issues during reloads or when using certain ASGI servers, instrumentation should occur within an `@app.on_event("startup")` function.
- gotcha When running FastAPI with multiple worker processes (e.g., using Gunicorn), Prometheus metrics require special handling. The `PROMETHEUS_MULTIPROC_DIR` environment variable must be set to a shared, writable directory.
Install
-
pip install prometheus-fastapi-instrumentator prometheus_client uvicorn
Imports
- Instrumentator
from prometheus_fastapi_instrumentator import Instrumentator
Quickstart
from fastapi import FastAPI
from prometheus_fastapi_instrumentator import Instrumentator
import uvicorn
import os
app = FastAPI()
# Best practice: Instrument the app on startup
@app.on_event("startup")
async def startup_event():
Instrumentator().instrument(app).expose(app)
print("Prometheus metrics exposed at /metrics")
@app.get("/")
async def read_root():
return {"message": "Hello Prometheus!"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id, "message": "An item"}
if __name__ == "__main__":
# For multiprocessing environments (e.g., Gunicorn with multiple workers),
# PROMETHEUS_MULTIPROC_DIR must be set to a shared writable directory.
# Example: os.environ["PROMETHEUS_MULTIPROC_DIR"] = "/tmp/prom_data"
uvicorn.run(app, host="0.0.0.0", port=8000)