温馨提示:本文翻译自stackoverflow.com,查看原文请点击:kubernetes - Reading Prometheus metric using python
kubernetes prometheus python

kubernetes - 使用python读取Prometheus指标

发布于 2020-04-17 13:37:00

我正在尝试在kubernetes中读取POD的Prometheus指标(cpu和内存值)。我安装了Prometheus,并且使用本地主机' http:// localhost:9090 /进行了所有安装我使用以下代码读取了pod的CPU和内存,但结果为error = response.json()['data'] ['result'],无法解码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))

查看更多

提问者
10101
被浏览
98
MOBT 2020-02-06 06:56

代码看起来正确,但是,您的response命令中的查询错误。真正的伙伴是:

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

您可以将“ container_cpu_user_seconds_total”更改为要读取的任何查询。.. 祝好运