Skip to content

Commit 39a62af

Browse files
authored
Fastapi + Gunicorn example in README (#812)
Also provided additional multiprocessing instructions for FastAPI + Gunicorn setup with code examples as per this issue: #810 Signed-off-by: Matas Minelga <[email protected]>
1 parent 8bbd16f commit 39a62af

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,55 @@ uwsgi --http 127.0.0.1:8000 --wsgi-file myapp.py --callable app
416416

417417
Visit http://localhost:8000/metrics to see the metrics
418418

419+
#### FastAPI + Gunicorn
420+
421+
To use Prometheus with [FastAPI](https://fastapi.tiangolo.com/) and [Gunicorn](https://gunicorn.org/) we need to serve metrics through a Prometheus ASGI application.
422+
423+
Save the snippet below in a `myapp.py` file
424+
425+
```python
426+
from fastapi import FastAPI
427+
from prometheus_client import make_asgi_app
428+
429+
# Create app
430+
app = FastAPI(debug=False)
431+
432+
# Add prometheus asgi middleware to route /metrics requests
433+
metrics_app = make_asgi_app()
434+
app.mount("/metrics", metrics_app)
435+
```
436+
437+
For Multiprocessing support, use this modified code snippet. Full multiprocessing intstructions are provided [here](https://github.com/prometheus/client_python#multiprocess-mode-eg-gunicorn).
438+
439+
```python
440+
from fastapi import FastAPI
441+
from prometheus_client import make_asgi_app
442+
443+
app = FastAPI(debug=False)
444+
445+
# Using multiprocess collector for registry
446+
def make_metrics_app():
447+
registry = CollectorRegistry()
448+
multiprocess.MultiProcessCollector(registry)
449+
return make_asgi_app(registry=registry)
450+
451+
452+
metrics_app = make_metrics_app()
453+
app.mount("/metrics", metrics_app)
454+
```
455+
456+
Run the example web application like this
457+
458+
```bash
459+
# Install gunicorn if you do not have it
460+
pip install gunicorn
461+
# If using multiple workers, add `--workers n` parameter to the line below
462+
gunicorn -b 127.0.0.1:8000 myapp:app -k uvicorn.workers.UvicornWorker
463+
```
464+
465+
Visit http://localhost:8000/metrics to see the metrics
466+
467+
419468
### Node exporter textfile collector
420469

421470
The [textfile collector](https://github.com/prometheus/node_exporter#textfile-collector)

0 commit comments

Comments
 (0)