Textfile Collector write_to_textfile function overwriting metric with same name but different labels

101 views
Skip to first unread message

Daniel Lacher

unread,
Feb 17, 2021, 11:35:47 PM2/17/21
to Prometheus Users
Greetings Prometheus users,

I have a function that is called a few times within a loop, and my idea was that the function would populate the .prom file by adding a new line every time, with the same metric name but with a different label. For example:

sv_api_response{method="getUserByID"} 1
sv_api_response{method="getUserByName"} 1
Etc. (1 when the API sends a 200 response, 0 otherwise)

But that doesn't happen. When the loop ends, I have only one line in the file, with the last written metric. Each time a new metric is written, it overwrites the previous one. My function is as follows:

from prometheus_client import CollectorRegistry, Gauge, write_to_textfile
...
def write_metric(method, expectation, response, region):
    registry = CollectorRegistry()
    gauge = Gauge('sv_api_response', '1 if API is up', ['method'], registry=registry)
    if response is not None:
        if response.status_code == expectation:
            gauge.labels(method).set(1)
        else:
            gauge.labels(method).set(0)
    else:
        gauge.labels(method).set(0)
    write_to_textfile('/opt/node_exporter/textfile_collector/sv.prom', registry)

Is there a way to make it preserve the metrics that it adds to the file and simply append the new ones?

Thank you.

Regards,
Daniel
Reply all
Reply to author
Forward
0 new messages