How to add custom path to Python prometheus_client

1,069 views
Skip to first unread message

Azzam S.A

unread,
Feb 25, 2021, 12:51:56 AM2/25/21
to Prometheus Users

I want to add a custom `/health` path in Python prometheus_client.
I am using Flask and Gunicorn for this.
Unfortunately, it doesn't work. I have tried:

```python
from flask import Flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from prometheus_client import make_wsgi_app
from prometheus_client.core import REGISTRY
from exporter.collector import Collector

REGISTRY.register(Collector())
app = Flask(__name__)

def health():
    return {"status": "running", "build": "111"}

app.wsgi_app = DispatcherMiddleware(
    app.wsgi_app, {"/metrics": make_wsgi_app(), "/health": health()}
)
```

I also try to use flask `@app.route` decorator. But dosn't work too:

```python
@app.route("/health")
def health():
    return {"status": "running", "build": "111"}


app.wsgi_app = DispatcherMiddleware(
    app.wsgi_app, {"/metrics": make_wsgi_app(), "/health": health()}
)

```

Any endpoint (even undefined such `/foo`) will produce the same content as `/metrics`


Azzam S.A

unread,
Feb 25, 2021, 1:39:32 AM2/25/21
to Prometheus Users
Mimicking `prometheus_client` code also doesn't work for me.

```python
def make_wsgi_custom():
    def health(environ, start_response):
        status = "200 OK"
        output = "Hello World!\n"
        response_headers = [
            ("Content-type", "text/plain"),
            ("Content-Length", str(len(output))),
        ]
        start_response(status, response_headers)
        return [output]

    return health


app.wsgi_app = DispatcherMiddleware(
    app.wsgi_app, {"/metrics": make_wsgi_app(), "/health": make_wsgi_custom()}
)
```

I think I need to use [Multiprocess Mode (Gunicorn)](https://github.com/prometheus/client_python#multiprocess-mode-gunicorn). But it comes with many limitations.
Maybe I will put the health info (buld number) inside the `/matrics` too

Azzam S.A

unread,
Mar 6, 2021, 10:51:21 PM3/6/21
to Prometheus Users
Fortunately, I mange to solve it.


```

from flask import Flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from prometheus_client import make_wsgi_app
from prometheus_client.core import REGISTRY

app = Flask(__name__)

def health(environ, start_response):
    headers = [("content-type", "application/json")]
    status = "200 OK"

    output = json.dumps({"data": {"status": "running"})
    output_encoded = output.encode("utf-8")

    start_response(status, headers)
    return [output_encoded]


app.wsgi_app = DispatcherMiddleware(
    app.wsgi_app, {"/metrics": make_wsgi_app(), "/health": util.health}
)
```
Reply all
Reply to author
Forward
0 new messages