python promethues_client 模块开发 exporter

简介: python promethues_client 模块开发 exporter

python 模块 promethues_client 开发 exporter

文章目录python 模块 promethues_client 开发 exporter

1. 介绍

2. 安装

3. 如何启动一个prometheus client

3.1 start_http_server方法

3.2 Flask编写promtheus client

4. LABELS配置

5. REGISTRY

6. Metrics自定义

6.1 Counter

6.2 gauge

6.3 histogram

6.4 summary

1. 介绍

promethues_client模块为开放prometheus客户端,自定义监控指标。

2. 安装

pip install prometheus_client

3. 如何启动一个prometheus client

3.1 start_http_server方法

#---coding:utf-8
from prometheus_client import Gauge,start_http_server  
import random  
from prometheus_client import Gauge  
a = Gauge('a', 'Description of gauge')  
a.set(345)   #value自己定义,但是一定要为 整数或者浮点数  
g = Gauge('g', 'Description of gauge',['mylabelname'])  
#此时一定要注意,定义Gague标签的时候是一个列表,列表可以存多个lablename,类型是字符串  
#在给lable定义value的时候也要注意,mylablename 这里是一个方法,或者说是一个变量了,一定要注意.  
start_http_server(8000)  
while True:  
      g.labels(mylabelname='ghost').set(random.random()) 

运行python client1.py,访问:http://127.0.0.1:8000

.....
python_info{implementation="CPython",major="2",minor="7",patchlevel="5",version="2.7.5"} 1.0
# HELP a Description of gauge
# TYPE a gauge
a 345.0
......
# TYPE g gauge
g{mylabelname="ghost"} 0.4350908628997736

3.2 Flask编写promtheus client

import prometheus_client
from prometheus_client import Counter
from flask import Response, Flask
app = Flask(__name__)
requests_total = Counter("request_count_xxx", "Total request cout of the host")
@app.route("/metrics")
def requests_count():
  requests_total.inc()
  # requests_total.inc(2)
  return Response(prometheus_client.generate_latest(requests_total),
          mimetype="text/plain")
@app.route('/')
def index():
  requests_total.inc()
  return "Welcome to China"
if __name__ == "__main__":
  app.run(host="0.0.0.0")

访问http://127.0.0.1:5000,返回:

Welcome to China

访问http://127.0.0.1:5000metrics,返回:

# HELP request_count_total Total request cout of the host
# TYPE request_count_total counter
request_count_xxx_total 2.0
# HELP request_count_created Total request cout of the host
# TYPE request_count_created gauge
request_count_xxx_created 1.594264948484944e+09

4. LABELS配置

使用labels来区分metric的特征

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()

5. REGISTRY

from prometheus_client import Counter, Gauge
from prometheus_client.core import CollectorRegistry
REGISTRY = CollectorRegistry(auto_describe=False)
requests_total = Counter("request_count", "Total request cout of the host", registry=REGISTRY)
random_value = Gauge("random_value", "Random value of the request", registry=REGISTRY)

6. Metrics自定义

Prometheus提供4种类型Metrics:Counter, Gauge, SummaryHistogram

定义4种metrics例子

metrics名字, metrics说明, metrics支持的label
c = Counter('cc', 'A counter')
g = Gauge('gg', 'A gauge')
h = Histogram('hh', 'A histogram', buckets=(-5, 0, 5))
s = Summary('ss', 'A summary', ['label1', 'label2'])  

6.1 Counter

一直累加的计数器,不可以减少。

以上面代码为例,多次访问http://127.0.0.1:5000metricsrequest_count_xxx_total持续增加。

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

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

它的唯一方法就是inc,只允许增加不允许减少:

 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)

counter适合用来记录访问总次数之类的,通过promql可以计算counter的增长速率,即可以得到类似的QPS诸多指标。

调用

# counter:  只增不减
c.inc()

输出metrics

# HELP cc_total A counter
# TYPE cc_total counter
cc_total 46.0
# TYPE cc_created gauge
cc_created 1.546424546634121e+09

说明:

  • #HELP是cc的注释说明,我们刚才定义的时候指定的;
  • #TYPE说明cc是一个counter;
  • cc这个counter被输出为cc_total;
  • cc_created这个输出的TYPE是gauge类型,记录了cc这个metrics的创建时间。

6.2 gauge

gauge可增可减,可以任意设置,就代表了某个指标当前的值而已。

比如可以设置当前的CPU温度,内存使用量等等,它们都是上下浮动的,不是只增不减的。

定义:第一个是metrics的名字,第二个是描述。

g = Gauge('gg', 'A gauge')

方法:

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))

调用:

这里每次设置一个随机值,其值可以是任意浮点数:

# gauge: 任意值
 g.set(random.random())

输出metrics:

# HELP gg A gauge
# TYPE gg gauge
gg 0.935768437404028

6.3 histogram

主要用来统计百分位。

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


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

定义:

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

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

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

方法:

while True:
    # histogram: 任意值, 会给符合条件的bucket增加1次计数
    h.observe(random.randint(-5, 5))

输出metrics:

# HELP hh A histogram
# TYPE hh histogram
hh_bucket{le="-5.0"} 12.0
hh_bucket{le="0.0"} 83.0
hh_bucket{le="5.0"} 153.0
hh_bucket{le="+Inf"} 153.0
hh_count 153.0
hh_sum -16.0
# TYPE hh_created gauge
hh_created 1.546499508889123e+09

描述:

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

6.4 summary


参考:


https://prometheus.io/docs/practices/histograms/

鱼儿的博客

用Python编写Prometheus监控的方法

Python prometheus_client使用方式

Python Metric 示例

prometheus_client.Counter


相关文章
Grafana实现图表双Y坐标轴展示
Grafana实现图表双Y坐标轴展示
|
1月前
|
人工智能 JavaScript Linux
OpenClaw 原版和汉化版windows 和Linux 下的部署实践
OpenClaw(原Clawdbot/Moltbot)是由彼得·斯坦伯格开发的开源个人AI代理,以“龙虾”为标识,口号“The AI that actually does things”。支持软件操作与长期记忆,2026年获Karpathy公开提及。提供中英文版本,基于TypeScript,可本地部署。
6773 131
|
4月前
|
监控 应用服务中间件 nginx
Agentic 时代必备技能:手把手为 Dify 应用构建全链路可观测系统
本文讲述 Dify 平台在 Agentic 应用开发中面临的可观测性挑战,从开发者与运维方双重视角出发,系统分析了当前 Dify 可观测能力的现状、局限与改进方向。
871 77
|
安全 机器人 Python
python之钉钉机器人自动发消息——傻瓜式教程
自动化跑完的结果,需要自动发送到钉钉群,自动将数据、报告、截图等保存至公司内部服务器,钉钉通知的时候,需要有个链接,点击就可以跳转。
4212 0
python之钉钉机器人自动发消息——傻瓜式教程
|
存储 Kubernetes 开发工具
使用ArgoCD管理Kubernetes部署指南
ArgoCD 是一款基于 Kubernetes 的声明式 GitOps 持续交付工具,通过自动同步 Git 存储库中的配置与 Kubernetes 集群状态,确保一致性与可靠性。它支持实时同步、声明式设置、自动修复和丰富的用户界面,极大简化了复杂应用的部署管理。结合 Helm Charts,ArgoCD 提供模块化、可重用的部署流程,显著减少人工开销和配置错误。对于云原生企业,ArgoCD 能优化部署策略,提升效率与安全性,是实现自动化与一致性的理想选择。
804 0
|
Kubernetes NoSQL Redis
k8s快速部署Redis单机
k8s快速部署Redis单机
|
人工智能 Prometheus 监控
容器化AI模型的监控与治理:确保模型持续稳定运行
在前几篇文章中,我们探讨了AI模型的容器化部署及构建容器化机器学习流水线。然而,将模型部署到生产环境只是第一步,更重要的是确保其持续稳定运行并保持性能。为此,必须关注容器化AI模型的监控与治理。 监控和治理至关重要,因为AI模型在生产环境中面临数据漂移、概念漂移、模型退化和安全风险等挑战。全面的监控涵盖模型性能、数据质量、解释性、安全性和版本管理等方面。使用Prometheus和Grafana可有效监控性能指标,而遵循模型治理最佳实践(如建立治理框架、定期评估、持续改进和加强安全)则能进一步提升模型的可信度和可靠性。总之,容器化AI模型的监控与治理是确保其长期稳定运行的关键。
|
Prometheus 监控 Cloud Native
Grafana 入门指南:快速上手监控仪表盘
【8月更文第29天】Grafana 是一款开源的数据可视化和监控工具,它允许用户轻松地创建美观的仪表盘和图表,以便更好地理解和监控数据。无论您是需要监控系统性能指标、应用程序日志还是业务关键指标,Grafana 都能提供灵活而强大的解决方案。本指南将带领您快速上手 Grafana,包括安装、配置以及创建第一个监控面板。
3821 1
|
Prometheus 监控 Cloud Native
prometheus学习笔记之Grafana安装与配置
prometheus学习笔记之Grafana安装与配置
3502 2