使用 python 读取 Prometheus 指标

Reading Prometheus metric using python

我正在尝试读取 kubernetes 中 POD 的 Prometheus 指标(cpu 和内存值)。我安装了 Prometheus,一切都在使用本地主机 'http://localhost:9090/。我使用以下代码读取 pod 的 CPU 和内存,但出现错误结果 = response.json()['data']['result'] , No JSON 对象可以被解码。有人可以帮忙吗?

import datetime
import time
import requests  

PROMETHEUS = 'http://localhost:9090/'

end_of_month = datetime.datetime.today().replace(day=1).date()

last_day = end_of_month - datetime.timedelta(days=1)
duration = '[' + str(last_day.day) + 'd]'

response = requests.get(PROMETHEUS + '/metrics',
  params={
    'query': 'sum by (job)(increase(process_cpu_seconds_total' + duration + '))',
    'time': time.mktime(end_of_month.timetuple())})
results = response.json()['data']['result']

print('{:%B %Y}:'.format(last_day))
for result in results:
  print(' {metric}: {value[1]}'.format(**result))

<prom-server-ip>:9090/metrics returns Prometheus 服务器本身的 Prometheus 指标(不是 JSON 格式)执行 GET 请求。

由于您正在尝试执行查询,因此您需要使用 /api/v1/query/api/v1/query_range 等 HTTP API 端点,而不是使用 /metrics.

$ curl 'http://localhost:9090/api/v1/query?query=up&time=2015-07-01T20:10:51.781Z'
{
   "status" : "success",
   "data" : {
      "resultType" : "vector",
      "result" : [
         {
            "metric" : {
               "__name__" : "up",
               "job" : "prometheus",
               "instance" : "localhost:9090"
            },
            "value": [ 1435781451.781, "1" ]
         },
         {
            "metric" : {
               "__name__" : "up",
               "job" : "node",
               "instance" : "localhost:9100"
            },
            "value" : [ 1435781451.781, "0" ]
         }
      ]
   }
}

有关更多详细信息,请访问 Prometheus official docs

代码看起来是正确的,但是,您的响应命令中的查询是错误的。真正的甲酸是:

response =requests.get(PROMETHEUS + '/api/v1/query', params={'query': 'container_cpu_user_seconds_total'}) 

您可以将 "container_cpu_user_seconds_total" 更改为您想要阅读的任何查询。 .. 祝你好运

您使用了错误的端点。 docs 建议的正确端点应该是查询接口,就像

http://pushgateway.example.org:9091/api/v1/status

要在 python 中做到这一点,只需使用 json 包。

import json
txt = requests.get(PROMETHEUS+'api/v1/metrics').text
j = json.loads(txt)
print(j['data'])