如何基于Python和Flask编写Prometheus监控


Posted in Python onNovember 25, 2020

介绍

Prometheus 的基本原理是通过 HTTP 周期性抓取被监控组件的状态。

任意组件只要提供对应的 HTTP 接口并且符合 Prometheus 定义的数据格式,就可以接入 Prometheus 监控。

Prometheus Server 负责定时在目标上抓取 metrics(指标)数据并保存到本地存储。它采用了一种 Pull(拉)的方式获取数据,不仅降低客户端的复杂度,客户端只需要采集数据,无需了解服务端情况,也让服务端可以更加方便地水平扩展。

如果监控数据达到告警阈值,Prometheus Server 会通过 HTTP 将告警发送到告警模块 alertmanger,通过告警的抑制后触发邮件或者 Webhook。Prometheus 支持 PromQL 提供多维度数据模型和灵活的查询,通过监控指标关联多个 tag 的方式,将监控数据进行任意维度的组合以及聚合。

在python中实现服务器端,对外提供接口。在Prometheus中配置请求网址,Prometheus会定期向该网址发起申请获取你想要返回的数据。

另外Prometheus提供4种类型Metrics:Counter, Gauge, Summary和Histogram。

准备

pip install flask
pip install prometheus_client

Counter

Counter可以增长,并且在程序重启的时候会被重设为0,常被用于访问量,任务个数,总处理时间,错误个数等只增不减的指标。

定义它需要2个参数,第一个是metrics的名字,第二个是metrics的描述信息:

c = Counter('c1', 'A counter')

counter只能增加,所以只有一个方法:

def inc(self, amount=1):
    '''Increment counter by the given amount.'''
    if amount < 0:
      raise ValueError('Counters can only be incremented by non-negative amounts.')
    self._value.inc(amount)

测试示例:

import prometheus_client
from prometheus_client import Counter
from prometheus_client.core import CollectorRegistry

from flask import Response, Flask

app = Flask(__name__)
requests_total = Counter('c1','A counter')

@app.route("/api/metrics/count/")
def requests_count():
 requests_total.inc(1)
 # requests_total.inc(2)
 return Response(prometheus_client.generate_latest(requests_total),mimetype="text/plain")


if __name__ == "__main__":
 app.run(host="127.0.0.1",port=8081)

访问http://127.0.0.1:8081/api/metrics/count/:

# HELP c1_total A counter
# TYPE c1_total counter
c1_total 1.0
# HELP c1_created A counter
# TYPE c1_created gauge
c1_created 1.6053265493727107e+09

HELP是c1的注释说明,创建Counter定义的。

TYPE是c1的类型说明。

c1_total为我们定义的指标输出:你会发现多了后缀_total,这是因为OpenMetrics与Prometheus文本格式之间的兼容性,OpenMetrics需要_total后缀。

gauge

gauge可增可减,可以任意设置。

比如可以设置当前的CPU温度,内存使用量,磁盘、网络流量等等。

定义和counter基本一样:

from prometheus_client import Gauge
g = Gauge('my_inprogress_requests', 'Description of gauge')
g.inc()   # Increment by 1
g.dec(10)  # Decrement by given value
g.set(4.2)  # Set to a given value

方法:

def inc(self, amount=1):
   '''Increment gauge by the given amount.'''
   self._value.inc(amount)

def dec(self, amount=1):
   '''Decrement gauge by the given amount.'''
   self._value.inc(-amount)

 def set(self, value):
   '''Set gauge to the given value.'''
   self._value.set(float(value))

测试示例:

import random
import prometheus_client
from prometheus_client import Gauge
from prometheus_client.core import CollectorRegistry
from flask import Response, Flask


app = Flask(__name__)
random_value = Gauge("g1", 'A gauge')
@app.route("/api/metrics/gauge/")
def r_value():
  random_value.set(random.randint(0, 10))
  return Response(prometheus_client.generate_latest(random_value),
          mimetype="text/plain")

if __name__ == "__main__":
 app.run(host="127.0.0.1",port=8081)

访问http://127.0.0.1:8081/api/metrics/gauge/

# HELP g1 A gauge
# TYPE g1 gauge
g1 5.0

LABELS的用法

使用labels来区分metric的特征,一个指标可以有其中一个label,也可以有多个label。

from prometheus_client import Counter
c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip'])
c.labels('get', '127.0.0.1').inc()
c.labels('post', '192.168.0.1').inc(3)
c.labels(method="get", clientip="192.168.0.1").inc()
import random
import prometheus_client
from prometheus_client import Gauge
from flask import Response, Flask


app = Flask(__name__)
c = Gauge("c1", 'A counter',['method','clientip'])
@app.route("/api/metrics/counter/")
def r_value():
  c.labels(method='get',clientip='192.168.0.%d' % random.randint(1,10)).inc()
  return Response(prometheus_client.generate_latest(c),
          mimetype="text/plain")

if __name__ == "__main__":
 app.run(host="127.0.0.1",port=8081)

连续访问9次http://127.0.0.1:8081/api/metrics/counter/:

# HELP c1 A counter
# TYPE c1 gauge
c1{clientip="192.168.0.7",method="get"} 2.0
c1{clientip="192.168.0.1",method="get"} 1.0
c1{clientip="192.168.0.8",method="get"} 1.0
c1{clientip="192.168.0.5",method="get"} 2.0
c1{clientip="192.168.0.4",method="get"} 1.0
c1{clientip="192.168.0.10",method="get"} 1.0
c1{clientip="192.168.0.2",method="get"} 1.0

histogram

这种主要用来统计百分位的,什么是百分位?英文叫做quantiles。

比如你有100条访问请求的耗时时间,把它们从小到大排序,第90个时间是200ms,那么我们可以说90%的请求都小于200ms,这也叫做”90分位是200ms”,能够反映出服务的基本质量。当然,也许第91个时间是2000ms,这就没法说了。

实际情况是,我们每天访问量至少几个亿,不可能把所有访问数据都存起来,然后排序找到90分位的时间是多少。因此,类似这种问题都采用了一些估算的算法来处理,不需要把所有数据都存下来,这里面数学原理比较高端,我们就直接看看prometheus的用法好了。

首先定义histogram:

h = Histogram('hh', 'A histogram', buckets=(-5, 0, 5))

第一个是metrics的名字,第二个是描述,第三个是分桶设置,重点说一下buckets。

这里(-5,0,5)实际划分成了几种桶:(无穷小,-5],(-5,0],(0,5],(5,无穷大)。

如果我们喂给它一个-8:

h.observe(8)

那么metrics会这样输出:

# HELP hh A histogram
# TYPE hh histogram
hh_bucket{le="-5.0"} 0.0
hh_bucket{le="0.0"} 0.0
hh_bucket{le="5.0"} 0.0
hh_bucket{le="+Inf"} 1.0
hh_count 1.0
hh_sum 8.0

hh_sum记录了observe的总和,count记录了observe的次数,bucket就是各种桶了,le表示<=某值。

可见,值8<=无穷大,所以只有最后一个桶计数了1次(注意,桶只是计数,bucket作用相当于统计样本在不同区间的出现次数)。

bucket的划分需要我们根据数据的分布拍脑袋指定,合理的划分可以让promql估算百分位的时候更准确,我们使用histogram的时候只需要知道先分好桶,再不断的打点即可,最终百分位的计算可以基于histogram的原始数据完成。

测试示例:

import random
import prometheus_client
from prometheus_client import Histogram
from flask import Response, Flask
app = Flask(__name__)
h = Histogram("h1", 'A Histogram', buckets=(-5, 0, 5))
@app.route("/api/metrics/histogram/")
def r_value():
  h.observe(random.randint(-5, 5))
  return Response(prometheus_client.generate_latest(h),
          mimetype="text/plain")

if __name__ == "__main__":
 app.run(host="127.0.0.1",port=8081)

连续访问http://127.0.0.1:8081/api/metrics/histogram/:

# HELP h1 A Histogram
# TYPE h1 histogram
h1_bucket{le="-5.0"} 0.0
h1_bucket{le="0.0"} 5.0
h1_bucket{le="5.0"} 10.0
h1_bucket{le="+Inf"} 10.0
h1_count 10.0
# HELP h1_created A Histogram
# TYPE h1_created gauge
h1_created 1.6053319432993534e+09

summary

python客户端没有完整实现summary算法,这里不介绍。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中eval带来的潜在风险代码分析
Dec 11 Python
Python多继承原理与用法示例
Aug 23 Python
Python实现登陆文件验证方法
Oct 06 Python
Python3模拟登录操作实例分析
Mar 12 Python
python 计算平均平方误差(MSE)的实例
Jun 29 Python
python实现飞机大战小游戏
Nov 08 Python
Macbook安装Python最新版本、GUI开发环境、图像处理、视频处理环境详解
Feb 17 Python
基于python纯函数实现井字棋游戏
May 27 Python
Pandas把dataframe或series转换成list的方法
Jun 14 Python
Python使用pyexecjs代码案例解析
Jul 13 Python
python 解决selenium 中的 .clear()方法失效问题
Sep 01 Python
Python连接mysql方法及常用参数
Sep 01 Python
python3爬虫中多线程进行解锁操作实例
Nov 25 #Python
mac系统下安装pycharm、永久激活、中文汉化详细教程
Nov 24 #Python
python 基于wx实现音乐播放
Nov 24 #Python
Python WebSocket长连接心跳与短连接的示例
Nov 24 #Python
Python 利用Entrez库筛选下载PubMed文献摘要的示例
Nov 24 #Python
python实现企业微信定时发送文本消息的示例代码
Nov 24 #Python
python爬虫快速响应服务器的做法
Nov 24 #Python
You might like
咖啡界又出新概念,无需咖啡豆的分子咖啡
2021/03/03 咖啡文化
php实现在限定区域里自动调整字体大小的类实例
2015/04/02 PHP
一些常用的JS功能函数(2009-06-04更新)
2009/06/04 Javascript
IE7中javascript操作CheckBox的checked=true不打勾的解决方法
2009/12/07 Javascript
B/S模式项目中常用的javascript汇总
2013/12/17 Javascript
原生javaScript做得动态表格(注释写的很清楚)
2013/12/29 Javascript
avalonjs制作响应式瀑布流特效
2015/05/06 Javascript
jQuery实现的简洁下拉菜单导航效果代码
2015/08/26 Javascript
学习JavaScript设计模式之单例模式
2016/01/19 Javascript
js将json格式的对象拼接成复杂的url参数方法
2016/05/25 Javascript
Jquery和BigFileUpload实现大文件上传及进度条显示
2016/06/27 Javascript
js 单引号替换成双引号,双引号替换成单引号的实现方法
2017/02/16 Javascript
jQuery插件FusionCharts实现的2D柱状图效果示例【附demo源码下载】
2017/03/06 Javascript
bootstrap栅格系统示例代码分享
2017/05/22 Javascript
node.js利用socket.io实现多人在线匹配联机五子棋
2018/05/31 Javascript
node.js调用C++函数的方法示例
2018/09/21 Javascript
vue.js的状态管理vuex中store的使用详解
2019/11/08 Javascript
Vue实现简易购物车页面
2020/12/30 Vue.js
python实现类似ftp传输文件的网络程序示例
2014/04/08 Python
Python使用正则表达式实现文本替换的方法
2017/04/18 Python
利用Python实现Windows下的鼠标键盘模拟的实例代码
2017/07/13 Python
修复 Django migration 时遇到的问题解决
2018/06/14 Python
django 实现电子支付功能的示例代码
2018/07/25 Python
Python模块、包(Package)概念与用法分析
2019/05/31 Python
详解Python中的正斜杠与反斜杠
2019/08/09 Python
python利用os模块编写文件复制功能——copy()函数用法
2020/07/13 Python
Python lxml库的简单介绍及基本使用讲解
2020/12/22 Python
css3实现动画的三种方式
2020/08/24 HTML / CSS
html5 制作地图当前定位箭头的方法示例
2020/01/10 HTML / CSS
Qoo10马来西亚:全球时尚和引领潮流的购物市场
2016/08/25 全球购物
关于Java String的一道面试题
2013/09/29 面试题
安全演讲稿大全
2014/05/09 职场文书
小学爱国卫生月活动总结
2014/06/30 职场文书
建国大业观后感600字
2015/06/01 职场文书
SpringDataJPA在Entity中常用的注解介绍
2021/12/06 Java/Android
Go微服务项目配置文件的定义和读取示例详解
2022/06/21 Golang