rycus86 / prometheus_flask_exporter

Prometheus exporter for Flask applications
https://pypi.python.org/pypi/prometheus-flask-exporter
MIT License
646 stars 161 forks source link

How to add dynamic value in label for counter? #148

Closed ColdFire87 closed 1 year ago

ColdFire87 commented 1 year ago

I have the following code:

from random import randint

@app.route('/rolldice')  # requests tracked by default
@metrics.counter(name='roll_counter',
                 description='The number of rolls by roll value',
                 labels={'roll_value': value})
def rolldice():
    value = randint(1, 6)
    return str(value)

How can I make it such that the value generated inside the handler is added as a label?

From what I can see in the docs, I can only add labels based on information from the HTTP request.

Thanks!

rycus86 commented 1 year ago

Hello,

First off, consider if this is really what you want, depending on the number of different values you can return there, it might blow out metric cardinality, see some guidelines here: https://prometheus.io/docs/practices/naming/#labels

If you do have some well behaved values, then you can attach them to Flask requests (or responses, or session, or some global Flask objects) and get them at the end of the request from a lambda label handler, like lambda response: response.someattribute or lambda: flask.someobject.someattribute. Does this help?

ColdFire87 commented 1 year ago

yes, that's perfect... I didn't know I can use a lambda to compute a label

(the docs do have a few examples, but I must've missed them :)