2

This is my below code

def pushgateway(ip_addr, hostname, env_name, services, type):
"""Notify prometheus alerts via pushgateway"""
registry = CollectorRegistry()
label_keys=['ip','hostname','env_name']
label_values=[ip_addr, hostname, env_name]
for key, value in services.items():
   label_keys.append(key)
   label_values.append(value)
assert len(label_keys) == len(label_values).  # this is through
g = Gauge(type[0], f'process status for {type[0]}', label_keys)
g.labels(label_values).set(int(type[1]))
push_to_gateway('localhost:9091',job=f"{service}_{env_name}",registry=registry)

While executing I get this error, What am I doing wrong?

File "/home/username/.local/lib/python3.6/site-packages/prometheus_client/metrics.py", line 164, in labels
    raise ValueError('Incorrect label count') ValueError: Incorrect label count

Printing the values from metrics.py - I get the below:

print(f"{labelvalues} - {self._labelnames}") --> (('a', 'b', 'c'),) - ('a','b','c')

len(labelvalues) is 1 and labelvalues[1] is 3 and len(self._labelnames) is 3.

and assert fails:

if len(labelvalues) != len(self._labelnames):
   raise ValueError('Incorrect label count')

How to fix this ? should i pass it in a different format ?

Shunya
  • 2,344
  • 4
  • 16
  • 28
psadi
  • 149
  • 7

1 Answers1

2

You forgot to unwrap the array of label_values. Add * before label_values in this line:

g.labels(*label_values).set(int(type[1]))

Also note that the Gauge you create will not appear in the registry that you send to pushgateway. You need to pass registry to your Gauge class instantiation:

g = Gauge(type[0], f'process status for {type[0]}', label_keys, registry=registry)

If you don't do that, the metric goes into the default registry:

from prometheus_client import REGISTRY
anemyte
  • 17,618
  • 1
  • 24
  • 45
  • Yes this indeed works, I figured unwrapping the list later that day. Thanks for pointing out the registry part !! – psadi Oct 21 '21 at 04:00