通过程序将指标推送到 Prometheus Pushgateway [文本格式编辑]
简要概括
我将介绍如何从程序中将指标推送到Pushgateway。
在推送可能的度量指标格式中,有两种选项:文本格式和协议缓冲格式。本文将介绍如何使用文本格式进行推送。
请参考以下文章,了解如何在Protocol buffer格式中进行push操作:
从程序向Prometheus Pushgateway推送指标[使用Protocol buffer]。
各种语言的库
「Prometheus」客户端库中已经悄悄地实现了将指标推送到「Pushgateway」的push方法,这可能会有些意外,但是每种语言都有相应的库。
相关的文档已在下面介绍。
- Pushing metrics | Prometheus
因为示例代码也包含在内,所以很容易融入使用。
通常情况下,我认为使用上述的库会更好。
以下提供给希望重新发明车轮的人的信息。
如果你只需要实现提交度量指标的处理过程,也许不必特意使用库,这可能对你有一些参考价值。
Prometheus客户端数据规范
以下文件中记载了Prometheus Client Data的格式。
- Prometheus Client Data Exposition Format – Google ドキュメント
要实现POST请求的发送处理,请注意在请求体的末尾添加换行(空行)。该规范描述如下:最后一行必须以换行符结尾。
最后,如果没有换行符,将返回400 Bad Request响应代码,并且响应消息将显示为文本格式解析错误,位于第1行:无效的指标名称。
使用curl进行POST操作的步骤确认。
如果考虑生成与此curl命令发送的POST请求相同的POST请求,可以考虑使用程序编写。
cat <<EOF | curl --data-binary @- http://pushgateway.example.org:9091/metrics/job/some_job/instance/some_instance
# TYPE some_metric counter
some_metric{label="val1"} 42
# TYPE another_metric gauge
# HELP another_metric Just an example.
another_metric 2398.283
EOF
以下是示例代码。
用Python实现的度量值推送处理示例。
import requests
import textwrap
def push():
some_metric = 42
another_metric = 2398.283
data = textwrap.dedent('''
# TYPE some_metric counter
some_metric{label="val1"} {some_metric}
# TYPE another_metric gauge
# HELP another_metric Just an example.
another_metric {another_metric}
'''.format(some_metric=some_metric, another_metric=another_metric )) # 最終行に改行を入れないと400が返るので注意
res = post(data)
def post(data):
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
res = requests.post(
"http://pushgateway.example.org:9091/metrics/job/some_job/instance/some_instance", headers=headers, data=data)
if res.status_code != 200:
raise Exception("failed : {}".format(res.status_code))
return res
此外,由于curl命令的POST请求头是application/x-www-form-urlencoded,因此我在此程序中进行了相应的设置。然而,似乎并不需要特别指定这个。