[英]How to push metrics with Python and Prometheus Pushgateway
I wish to push a multi-labeled metric into Prometheus using the Pushgateway.我希望使用 Pushgateway 将多标签指标推送到 Prometheus。 The documentation offer a curl example but I need it sent via Python.
该文档提供了 curl 示例,但我需要通过 Python 发送它。 In addition, I'd like to embed multiple labels into the metric.
此外,我想在指标中嵌入多个标签。
Here's what I ended up doing - it took a while to get right.这就是我最终做的 - 花了一段时间才做对。 While ideally I would have used the Prometheus python client designed specifically for this purpose, it appears that it doesn't support multiple labels in some cases and the documentation is virtually non-existent - so I went with a home-brewed solution.
虽然理想情况下我会使用专门为此目的设计的 Prometheus python 客户端,但它似乎在某些情况下不支持多个标签,而且文档几乎不存在 - 所以我采用了自制解决方案。
The code below uses gevent and supports multiple (comma-delimited) pushgateway urls (like "pushgateway1.my.com:9092, pushgateway2.my.com:9092").下面的代码使用 gevent 并支持多个(逗号分隔的)pushgateway url(如“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)
这是为 Python 客户端记录的: https : //github.com/prometheus/client_python#exporting-to-a-pushgateway
One: Install the client:一:安装客户端:
pip install prometheus_client
Two: Paste the following into a Python interpreter:二:将以下内容粘贴到 Python 解释器中:
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 can't use prometheus_client
, here is short version of requests
:如果您不能使用
prometheus_client
,这里是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.可以在数据变量中的
\n
(新行)之后添加更多项目。
In one command and without any scripts:在一个命令中并且没有任何脚本:
echo "some_metric 3.14" | curl --data-binary @- http://pushgateway.example.org:9091/metrics/job/some_job
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.