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.
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.
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 .
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.
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.
This is documented for the Python client: https://github.com/prometheus/client_python#exporting-to-a-pushgateway
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With