prometheus / client_python

Prometheus instrumentation library for Python applications
Apache License 2.0
3.93k stars 794 forks source link

Remove child metric #711

Open hAh0L13 opened 2 years ago

hAh0L13 commented 2 years ago

Hello. Tried to remove some childs, but got KeyError.

My custom metric (gauge) have some lables and worked fine. But when i needed to delete some childs, i'm stuck:

global statusOK
statusOK = "OK"
global statusNOK
statusNOK = "Fail"

service_login_status_prom = prom.Gauge('service_login_status', 'Check access token availability', ['status', 'dc_name'])
result = str('0')
service_login_status_prom.labels(statusOK, dc_name).set(result)
service_login_status_prom.remove(statusNOK, dc_name)

https://github.com/prometheus/client_python/blob/09fb45953bac018a90e89f0b1e7bcd1d5d81c01b/prometheus_client/metrics.py#L187

Error is -

File "/usr/local/lib/python3.8/site-packages/prometheus_client/metrics.py", line 187, in remove

   del self._metrics[labelvalues]
   KeyError: ('Fail', '11u25')

When label is only one, error quite different -

File "/usr/local/lib/python3.8/site-packages/prometheus_client/metrics.py", line 187, in remove

   del self._metrics[labelvalues]
   KeyError: ('Fail', )

Comma at the end of labelvalues confused me

csmarchbanks commented 2 years ago

Hello, it looks like you are trying to remove a child that does not exist, thus KeyError is an appropriate response.

In the second example are you only passing one argument? The error could be improved some for that case.

cmarasescu commented 2 years ago

Hello @csmarchbanks ,

I also have this KeyError issue while trying to remove a child metric that is still there, as prometheus can see it. Can you provide a short example on how to call the remove method?

Thanks!

hAh0L13 commented 2 years ago

Hello @cmarasescu In my case, I rewrite it with clear() -

service_login_status_prom.clear()
cmarasescu commented 2 years ago

Hello @hAh0L13 ,

I've finally fixed my issue, it seems that I've just put the labels in a wrong order. Most likely your initial call was failing simply because there was no child metric matching your labels.