使用 prometheus python 库编写自定义指标的方法(完整代码)


Posted in Python onJune 29, 2020

虽然 prometheus 已有大量可直接使用的 exporter 可供使用,以满足收集不同的监控指标的需要。例如,node exporter 可以收集机器 cpu,内存等指标,cadvisor 可以收集容器指标。然而,如果需要收集一些定制化的指标,还是需要我们编写自定义的指标。

本文讲述如何使用 prometheus python 客户端库和 flask 编写 prometheus 自定义指标。

安装依赖库

我们的程序依赖于flask 和prometheus client 两个库,其 requirements.txt 内容如下:

flask==1.1.2
prometheus-client==0.8.0

运行 flask

我们先使用 flask web 框架将 /metrics 接口运行起来,再往里面添加指标的实现逻辑。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask
app = Flask(__name__)

@app.route('/metrics')
def hello():
 return 'metrics'

if __name__ == '__main__':
 app.run(host='0.0.0.0', port=5000)

打开浏览器,输入 http://127.0.0.1:5000/metrics,按下回车后浏览器显示 metrics 字符。

编写指标

Prometheus 提供四种指标类型,分别为 Counter,Gauge,Histogram 和 Summary。

Counter

Counter 指标只增不减,可以用来代表处理的请求数量,处理的任务数量,等。

可以使用 Counter 定义一个 counter 指标:

counter = Counter('my_counter', 'an example showed how to use counter')

其中,my_counter 是 counter 的名称,an example showed how to use counter 是对该 counter 的描述。

使用 counter 完整的代码如下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask, Response
from prometheus_client import Counter, generate_latest
app = Flask(__name__)
counter = Counter('my_counter', 'an example showed how to use counter')

@app.route('/metrics')
def hello():
 counter.inc(1)
 return Response(generate_latest(counter), mimetype='text/plain')

if __name__ == '__main__':
 app.run(host='0.0.0.0', port=5000)

访问 http://127.0.0.1:5000/metrics,浏览器输出:

# HELP my_counter_total an example showed how to use counter
# TYPE my_counter_total counter
my_counter_total 6.0
# HELP my_counter_created an example showed how to use counter
# TYPE my_counter_created gauge
my_counter_created 1.5932468510424378e+09

在定义 counter 指标时,可以定义其 label 标签:

counter = Counter('my_counter', 'an example showed how to use counter', ['machine_ip'])

在使用时指定标签的值:

counter.labels('127.0.0.1').inc(1)

这时浏览器会将标签输出:

my_counter_total{machine_ip="127.0.0.1"} 1.0

Gauge

Gauge 指标可增可减,例如,并发请求数量,cpu 占用率,等。

可以使用 Gauge 定义一个 gauge 指标:

registry = CollectorRegistry()
gauge = Gauge('my_gauge', 'an example showed how to use gauge', ['machine_ip'], registry=registry)

为使得 /metrics 接口返回多个指标,我们引入了 CollectorRegistry ,并设置 gauge 的 registry 属性。

使用 set 方法设置 gauge 指标的值:

gauge.labels('127.0.0.1').set(2)

访问 http://127.0.0.1:5000/metrics,浏览器增加输出:

# HELP my_gauge an example showed how to use gauge
# TYPE my_gauge gauge
my_gauge{machine_ip="127.0.0.1"} 2.0

Histogram

Histogram 用于统计样本数值落在不同的桶(buckets)里面的数量。例如,统计应用程序的响应时间,可以使用 histogram 指标类型。

使用 Histogram 定义一个 historgram 指标:

buckets = (100, 200, 300, 500, 1000, 3000, 10000, float('inf'))
histogram = Histogram('my_histogram', 'an example showed how to use histogram', ['machine_ip'], registry=registry, buckets=buckets)

如果我们不使用默认的 buckets,可以指定一个自定义的 buckets,如上面的代码所示。

使用 observe() 方法设置 histogram 的值:

histogram.labels('127.0.0.1').observe(1001)

访问 /metrics 接口,输出:

# HELP my_histogram an example showed how to use histogram
# TYPE my_histogram histogram
my_histogram_bucket{le="100.0",machine_ip="127.0.0.1"} 0.0
my_histogram_bucket{le="200.0",machine_ip="127.0.0.1"} 0.0
my_histogram_bucket{le="300.0",machine_ip="127.0.0.1"} 0.0
my_histogram_bucket{le="500.0",machine_ip="127.0.0.1"} 0.0
my_histogram_bucket{le="1000.0",machine_ip="127.0.0.1"} 0.0
my_histogram_bucket{le="3000.0",machine_ip="127.0.0.1"} 1.0
my_histogram_bucket{le="10000.0",machine_ip="127.0.0.1"} 1.0
my_histogram_bucket{le="+Inf",machine_ip="127.0.0.1"} 1.0
my_histogram_count{machine_ip="127.0.0.1"} 1.0
my_histogram_sum{machine_ip="127.0.0.1"} 1001.0
# HELP my_histogram_created an example showed how to use histogram
# TYPE my_histogram_created gauge
my_histogram_created{machine_ip="127.0.0.1"} 1.593260699767071e+09

由于我们设置了 histogram 的样本值为 1001,可以看到,从 3000 开始,xxx_bucket 的值为 1。由于只设置一个样本值,故 my_histogram_count 为 1 ,且样本总数 my_histogram_sum 为 1001。
读者可以自行试验几次,慢慢体会 histogram 指标的使用,远比看网上的文章理解得快。

Summary

Summary 和 histogram 类型类似,可用于统计数据的分布情况。

定义 summary 指标:

summary = Summary('my_summary', 'an example showed how to use summary', ['machine_ip'], registry=registry)

设置 summary 指标的值:

summary.labels('127.0.0.1').observe(randint(1, 10))

访问 /metrics 接口,输出:

# HELP my_summary an example showed how to use summary
# TYPE my_summary summary
my_summary_count{machine_ip="127.0.0.1"} 4.0
my_summary_sum{machine_ip="127.0.0.1"} 16.0
# HELP my_summary_created an example showed how to use summary
# TYPE my_summary_created gauge
my_summary_created{machine_ip="127.0.0.1"} 1.593263241728389e+09

附:完整源代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from random import randint
from flask import Flask, Response
from prometheus_client import Counter, Gauge, Histogram, Summary, \
 generate_latest, CollectorRegistry
app = Flask(__name__)
registry = CollectorRegistry()
counter = Counter('my_counter', 'an example showed how to use counter', ['machine_ip'], registry=registry)
gauge = Gauge('my_gauge', 'an example showed how to use gauge', ['machine_ip'], registry=registry)
buckets = (100, 200, 300, 500, 1000, 3000, 10000, float('inf'))
histogram = Histogram('my_histogram', 'an example showed how to use histogram',
  ['machine_ip'], registry=registry, buckets=buckets)
summary = Summary('my_summary', 'an example showed how to use summary', ['machine_ip'], registry=registry)

@app.route('/metrics')
def hello():
 counter.labels('127.0.0.1').inc(1)
 gauge.labels('127.0.0.1').set(2)
 histogram.labels('127.0.0.1').observe(1001)
 summary.labels('127.0.0.1').observe(randint(1, 10))
 return Response(generate_latest(registry), mimetype='text/plain')

if __name__ == '__main__':
 app.run(host='0.0.0.0', port=5000)

参考资料

https://github.com/prometheus/client_python
https://prometheus.io/docs/concepts/metric_types/
https://prometheus.io/docs/instrumenting/writing_clientlibs/
https://prometheus.io/docs/instrumenting/exporters/
https://pypi.org/project/prometheus-client/
https://prometheus.io/docs/concepts/metric_types/
http://www.coderdocument.com/docs/prometheus/v2.14/best_practices/histogram_and_summary.html
https://prometheus.io/docs/practices/histograms/

总结

到此这篇关于使用 prometheus python 库编写自定义指标的文章就介绍到这了,更多相关prometheus python 库编写自定义指标内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
django接入新浪微博OAuth的方法
Jun 29 Python
python 读写、创建 文件的方法(必看)
Sep 12 Python
python Selenium爬取内容并存储至MySQL数据库的实现代码
Mar 16 Python
Python插件virtualenv搭建虚拟环境
Nov 20 Python
python3+PyQt5实现自定义流体混合窗口部件
Apr 24 Python
详解Python下ftp上传文件linux服务器
Jun 21 Python
python3 自动识别usb连接状态,即对usb重连的判断方法
Jul 03 Python
Python如何使用队列方式实现多线程爬虫
May 12 Python
解决python调用自己文件函数/执行函数找不到包问题
Jun 01 Python
python 下划线的不同用法
Oct 24 Python
python3访问字典里的值实例方法
Nov 18 Python
Python线程池与GIL全局锁实现抽奖小案例
Apr 13 Python
使用keras时input_shape的维度表示问题说明
Jun 29 #Python
在Keras中CNN联合LSTM进行分类实例
Jun 29 #Python
使用keras实现BiLSTM+CNN+CRF文字标记NER
Jun 29 #Python
Python建造者模式案例运行原理解析
Jun 29 #Python
解决Keras中循环使用K.ctc_decode内存不释放的问题
Jun 29 #Python
Python根据指定文件生成XML的方法
Jun 29 #Python
keras在构建LSTM模型时对变长序列的处理操作
Jun 29 #Python
You might like
php 仿Comsenz安装效果代码打包提供下载
2010/05/09 PHP
php date()日期时间函数详解
2010/05/16 PHP
使用PHP curl模拟浏览器抓取网站信息
2013/10/28 PHP
laravel与thinkphp之间的区别与优缺点
2021/03/02 PHP
ExtJS TabPanel beforeremove beforeclose使用说明
2010/03/31 Javascript
jQuery的live()方法对hover事件的处理示例
2014/02/27 Javascript
jQuery里filter()函数与find()函数用法分析
2015/06/24 Javascript
javascript实现连续赋值
2015/08/10 Javascript
javascript中Date format(js日期格式化)方法小结
2015/12/17 Javascript
jQuery实现带水平滑杆的焦点图动画插件
2016/03/08 Javascript
JS获取子窗口中返回的数据实现方法
2016/05/28 Javascript
Node.js中如何合并两个复杂对象详解
2016/12/31 Javascript
浅谈Angular2 模块懒加载的方法
2017/10/04 Javascript
bootstrap table sum总数量统计实现方法
2017/10/29 Javascript
详解webpack与SPA实践之开发环境搭建
2017/12/18 Javascript
详解webpack打包nodejs项目(前端代码)
2018/09/19 NodeJs
jQuery动态操作表单示例【基于table表格】
2018/12/06 jQuery
使用element-ui table expand展开行实现手风琴效果
2019/03/15 Javascript
微信小程序拼接图片链接无底洞深入探究
2019/09/03 Javascript
vue组件入门知识全梳理
2020/09/21 Javascript
Python的re模块正则表达式操作
2016/05/25 Python
Python程序员面试题 你必须提前准备!
2018/01/16 Python
详解Python3.6的py文件打包生成exe
2018/07/13 Python
Python基于class()实现面向对象原理详解
2020/03/26 Python
python多进程下的生产者和消费者模型
2020/05/07 Python
PyQt5 控件字体样式等设置的实现
2020/05/13 Python
python 密码学示例——凯撒密码的实现
2020/09/21 Python
使用CSS3的rem属性制作响应式页面布局的要点解析
2016/05/24 HTML / CSS
美国知名的旅游网站:OneTravel
2018/10/09 全球购物
美国正宗设计师眼镜在线零售商:EYEZZ
2019/03/23 全球购物
在校生党员自我评价
2013/09/25 职场文书
图书馆志愿者活动总结
2014/06/27 职场文书
党内外群众意见范文
2015/06/02 职场文书
罗马假日观后感
2015/06/08 职场文书
2015年治庸问责工作总结
2015/07/27 职场文书
Python中OpenCV实现查找轮廓的实例
2021/06/08 Python