介绍
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)
测试示例:
importprometheus_clientfrom prometheus_client importCounterfrom prometheus_client.core importCollectorRegistryfrom flask importResponse, Flask
app= Flask(__name__)
requests_total= Counter('c1','A