From a0c1e60b3508c1905123c332575243a7dfce90c9 Mon Sep 17 00:00:00 2001 From: Matas Minelga Date: Wed, 18 May 2022 11:48:48 +0300 Subject: [PATCH] Fastapi + Gunicorn example in README Also provided additional multiprocessing instructions for FastAPI + Gunicorn setup with code examples as per this issue: https://github.com/prometheus/client_python/issues/810 --- README.md | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/README.md b/README.md index b25a55b7..1cf86d81 100644 --- a/README.md +++ b/README.md @@ -404,6 +404,56 @@ uwsgi --http 127.0.0.1:8000 --wsgi-file myapp.py --callable app Visit http://localhost:8000/metrics to see the metrics +#### FastAPI + Gunicorn + +To use Prometheus with [FastAPI](https://fastapi.tiangolo.com/) and [Gunicorn](https://gunicorn.org/) we need to serve metrics through a Prometheus ASGI application. + +Save the snippet below in a `myapp.py` file + +```python +from fastapi import FastAPI +from prometheus_client import make_asgi_app + +# Create app +app = FastAPI(debug=False) + +# Add prometheus asgi middleware to route /metrics requests +metrics_app = make_asgi_app() +app.mount("/metrics", metrics_app) +``` + +For Multiprocessing support, use this modified code snippet. Full multiprocessing intstructions are provided [here](https://github.com/prometheus/client_python#multiprocess-mode-eg-gunicorn). + +```python +from fastapi import FastAPI +from prometheus_client import make_asgi_app + +app = FastAPI(debug=False) + +# Using multiprocess collector for registry +def make_metrics_app(): + registry = CollectorRegistry() + multiprocess.MultiProcessCollector(registry) + return prometheus_client.make_asgi_app(registry=registry) + + +metrics_app = make_metrics_app() +app.mount("/metrics", metrics_app)) + +``` + + +Run the example web application like this + +```bash +# Install gunicorn if you do not have it +pip install gunicorn +# If using multiple workers, add `--workers n` parameter to the line below +gunicorn -b 127.0.0.1:8000 myapp:app -k uvicorn.workers.UvicornWorker +``` + +Visit http://localhost:8000/metrics to see the metrics + ### Node exporter textfile collector The [textfile collector](https://github.com/prometheus/node_exporter#textfile-collector)