实验环境
- Prometheus: 2.20.0
- Python: 3.7.7
- Requests:2.24.0
首先要安装依赖,
sudo pip3 install requests==2.24.0
现状
你是否面临着如下这种数以千计的Prometheus业务指标要添加到Grafana图表里面做监控数据可视化
闲言少叙
直接上拉取Prometheus指标的接口的python脚本,自己跑一下,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/usr/bin/env python3 # coding = 'utf-8' import requests # 记得替换成你们自己的,不要忘记端口,末尾不要斜杠 host_url = "http://demo.robustperception.io:9090" prometheus_api = "/api/v1/label/__name__/values" data = requests.get(host_url + prometheus_api).json() f = open("metrics.txt",'w') for m in data['data']: f.write(m + '\n') f.close() |
小声说一下, 上面的Prometheus指标接口我一开始是不知道的,不得已写了个selenium+chromedriver的python动态爬虫把所有业务指标爬了下来,本篇博客就不展示这个爬虫代码了,如果/api/v1/label/__name__/values
这个接口在新版本的Prometheus中不存在了,你又急需这些指标可以在本站页脚找到博主的邮箱联系我临时花几分钟帮你写一个爬虫,我写这种爬虫是轻车熟路,另外小小提示一下,如果只用requests库的话是不行的,以及直接用 driver.page_source 获取html源码的话也是会有bug的,总之日后上面直接调接口的方法失败了,请直接联系我花点钱给你写个爬虫。
紧接着上生成Grafana查询语句的bash脚本,如下,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/bin/bash set -x # 考虑到业务的复杂性,这里必须传入你的业务应用名称, # 以便每个业务均生成一个单独的文件好让你把添加大量 # Grafana图表这种繁复的任务拆分给不同的人去做 APP_NAME=$1 results=`cat metrics.txt |grep $APP_NAME` for result in $results;do # 注意这里的grep后面的这个timer是指你们含有quantile变量的Grafana查询语句 # 对应的Prometheus指标的名称以什么结尾,请自行修改 result_check=`echo $result |grep 'timer$'` if [ -z $result_check ];then echo $result"{application=\"\$application\",instance=\"\$instance\"}" >> $APP_NAME.txt else echo $result"{application=\"\$application\",instance=\"\$instance\",quantile=\"\"}" >> $APP_NAME.txt fi done |
注意这是shell脚本哦,多余的我就不多说了,都在脚本注释里面,我们来直接看最终效果吧,如下: