Warm tip: This article is reproduced from stackoverflow.com, please click
kubernetes prometheus python

Reading Prometheus metric using python

发布于 2020-04-16 12:18:30

I am trying to read Prometheus metrics (the cpu and memory values) of a POD in kubernetes. I have Prometheus install and everything is up using local host 'http://localhost:9090/. I used the following code to read the CPU and memory of a pod but I have an error results = response.json()['data']['result'] , No JSON object could be decoded . IS anyone can help please ?

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))
Questioner
10101
Viewed
54
MOBT 2020-02-06 06:56

The code looks true, However,the query in your response command is wrong . the true formate is :

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

you can change "container_cpu_user_seconds_total" to any query that you want to read. .. good luck