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, Summary和Histogram

定义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:5000metrics,request_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


相关文章
|
Prometheus 监控 Cloud Native
一文带你吃透MySQL性能监控解决方案:Prometheus+Grafana
MySQL性能监控解决方案:Prometheus+Grafana问题描述 在对MySQL进行主从复制、分库分表等架构之后,MySQL的节点数量变得越来越多,无法实时监控到每一台MySQL节点,此时应当如何处理? 问题分析与解决方案 针对上面的问题,需要用Prometheus + Grafana对服务器进行统一监控、规划与报警,时刻关注服务器的响应情况。当出现宕机或异常时,Grafana可迅速通过短信、钉钉、邮件等方式通知相关人员,进而快速对生产环节进行补救。 Prometheus概述与适用场景 Prometheus 是 一 个 开 源 的 服 务 监 控 系 统 和 时 间 序 列 数 据
3069 0
|
12月前
|
人工智能 自然语言处理 API
一句话生成拓扑图!AI+Draw.io 封神开源组合,工具让你的效率爆炸
一句话生成拓扑图!next-ai-draw-io 结合 AI 与 Draw.io,通过自然语言秒出架构图,支持私有部署、免费大模型接口,彻底解放生产力,绘图效率直接爆炸。
5786 153
|
人工智能 安全 机器人
OpenClaw(原 Clawdbot)钉钉对接保姆级教程 手把手教你打造自己的 AI 助手
OpenClaw(原Clawdbot)是一款开源本地AI助手,支持钉钉、飞书等多平台接入。本教程手把手指导Linux下部署与钉钉机器人对接,涵盖环境配置、模型选择(如Qwen)、权限设置及调试,助你快速打造私有、安全、高权限的专属AI助理。(239字)
41254 184
|
10月前
|
人工智能 JavaScript Linux
OpenClaw 原版和汉化版windows 和Linux 下的部署实践
OpenClaw(原Clawdbot/Moltbot)是由彼得·斯坦伯格开发的开源个人AI代理,以“龙虾”为标识,口号“The AI that actually does things”。支持软件操作与长期记忆,2026年获Karpathy公开提及。提供中英文版本,基于TypeScript,可本地部署。
8690 132
|
敏捷开发 人工智能 数据可视化
让AI替你写用例!Dify+RAG工作流,一键生成覆盖率达90%的测试方案
本文介绍如何利用Dify.ai与RAG技术构建智能测试用例生成工作流,通过接入需求文档、API接口等知识库,实现高覆盖率(超90%)的自动化用例生成,显著提升测试效率与质量,解放测试人力,助力敏捷开发。
|
人工智能 运维 监控
MCP 打通AI大模型与 Zabbix,运维新时代来了!
管志勇,高级软件开发工程师、OceanBase认证专家,深耕软件开发多年,专注Zabbix运维开发与数据可视化。本文介绍其如何通过MCP协议实现大模型与Zabbix的智能联动,打造高效运维新范式。
1646 14
|
存储 Prometheus 监控
Prometheus 深度指南:设计理念 · PromQL · Exporter · Thanos
Prometheus 是一款开源的系统监控与报警工具,专为云原生环境设计。它采用拉取模型采集数据,内置高效的本地时序数据库(TSDB),支持丰富的指标类型和四个黄金指标(延迟、流量、错误、饱和度)。其查询语言 PromQL 功能强大,可灵活聚合和分析时间序列数据。此外,通过 Exporter 机制,Prometheus 能轻松扩展到各种系统和服务。针对大规模场景,Thanos 提供高可用解决方案,整合多 Prometheus 实例,实现全局视图和长期存储。整体架构简洁可靠,适用于动态分布式环境。
2249 10
Prometheus 深度指南:设计理念 · PromQL · Exporter · Thanos

热门文章

最新文章