How to promote metrics with Python and Prometheus Pushgateway

I want to push a multi-label metric into Prometheus using Pushgateway. The documentation offers an example of twisting, but I need to send it via Python. In addition, I would like to embed several labels in the metric.

+4
source share
2 answers

This is what I did in the end - it took time to get better. Ideally, I would use the Prometheus Python client, designed specifically for this purpose, it seems that it does not support multiple shortcuts in some cases, and the documentation practically does not exist - so I went with a home solution.

gevent ( -) URL- pushgateway (, "pushgateway1.my.com:9092, pushgateway2.my.com:9092" ).

import gevent
import requests

def _submit_wrapper(urls, job_name, metric_name, metric_value, dimensions):
    dim = ''
    headers = {'X-Requested-With': 'Python requests', 'Content-type': 'text/xml'}
    for key, value in dimensions.iteritems():
        dim += '/%s/%s' % (key, value)
    for url in urls:
        requests.post('http://%s/metrics/job/%s%s' % (url, job_name, dim),
                      data='%s %s\n' % (metric_name, metric_value), headers=headers)


def submit_metrics(job_name, metric_name, metric_value, dimensions={}):
    from ..app import config
    cfg = config.init()
    urls = cfg['PUSHGATEWAY_URLS'].split(',')
    gevent.spawn(_submit_wrapper, urls, job_name, metric_name, metric_value, dimensions)
+1

Source: https://habr.com/ru/post/1662922/


All Articles