Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push metrics with Python and Prometheus Pushgateway

I wish to push a multi-labeled metric into Prometheus using the Pushgateway. The documentation offer a curl example but I need it sent via Python. In addition, I'd like to embed multiple labels into the metric.

like image 605
FuzzyAmi Avatar asked Dec 06 '16 07:12

FuzzyAmi


People also ask

Can we push metrics to Prometheus?

Occasionally you will need to monitor components which cannot be scraped. The Prometheus Pushgateway allows you to push time series from short-lived service-level batch jobs to an intermediary job which Prometheus can scrape.

How do you expose metrics to Prometheus in Python?

Metrics are usually exposed over HTTP, to be read by the Prometheus server. Visit http://localhost:8000/ to view the metrics. To add Prometheus exposition to an existing HTTP server, see the MetricsHandler class which provides a BaseHTTPRequestHandler .

How do I use python with Prometheus?

To verify whether Prometheus is monitoring your Python app, navigate to the URL http://192.168.20.131:9090/targets from your favorite web browser. You should see that your python-app target is in the UP state. So, Prometheus can scrape metrics from your Python app.


3 Answers

If you can't use prometheus_client, here is short version of requests:

import requests

headers = {'X-Requested-With': 'Python requests', 'Content-type': 'text/xml'}
url = "https://pushgateway.example.com/metrics/job/job_name/instance/instance_name"
data = "websites_offline{website=\"example.com\"} 0\n"
r = requests.post(url, headers=headers, data=data)
print(r.reason)
print(r.status_code)

More items can be added after \n (new line) in a data variable.

like image 134
laimison Avatar answered Sep 18 '22 12:09

laimison


This is documented for the Python client: https://github.com/prometheus/client_python#exporting-to-a-pushgateway

like image 28
brian-brazil Avatar answered Sep 19 '22 12:09

brian-brazil


First step: Install the client:

pip install prometheus_client

Second step: Paste the following into a Python interpreter:

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

registry = CollectorRegistry()
g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registry=registry)
g.set_to_current_time()
push_to_gateway('localhost:9091', job='batchA', registry=registry)
like image 34
samuel161 Avatar answered Sep 16 '22 12:09

samuel161