Skip to content

Commit

Permalink
Fastapi + Gunicorn example in README (#812)
Browse files Browse the repository at this point in the history
Also provided additional multiprocessing instructions for FastAPI + Gunicorn setup with code examples as per this issue: #810

Signed-off-by: Matas Minelga <minematas@gmail.com>
  • Loading branch information
ashirviskas committed Apr 18, 2023
1 parent 8bbd16f commit 39a62af
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,55 @@ 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 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)
Expand Down

0 comments on commit 39a62af

Please sign in to comment.