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


相关文章
|
存储 Prometheus Cloud Native
Thanos 工作原理及组件简介
Thanos 工作原理及组件简介
|
11月前
|
Prometheus Kubernetes 监控
Kubernetes技巧:使用Prometheus监控Pod性能指标。
记住,监控和可视化是维持健康集群的必备工具,而Prometheus加上Grafana就是这个任务上的黄金搭档。安装这两位侦探后,你的Kubernetes集群将会像一个经过精心维护的庞大机器一样,高效、有序地运转。
909 21
|
存储 Prometheus 监控
Prometheus 深度指南:设计理念 · PromQL · Exporter · Thanos
Prometheus 是一款开源的系统监控与报警工具,专为云原生环境设计。它采用拉取模型采集数据,内置高效的本地时序数据库(TSDB),支持丰富的指标类型和四个黄金指标(延迟、流量、错误、饱和度)。其查询语言 PromQL 功能强大,可灵活聚合和分析时间序列数据。此外,通过 Exporter 机制,Prometheus 能轻松扩展到各种系统和服务。针对大规模场景,Thanos 提供高可用解决方案,整合多 Prometheus 实例,实现全局视图和长期存储。整体架构简洁可靠,适用于动态分布式环境。
1646 10
Prometheus 深度指南:设计理念 · PromQL · Exporter · Thanos
|
人工智能 Prometheus 监控
容器化AI模型的监控与治理:确保模型持续稳定运行
在前几篇文章中,我们探讨了AI模型的容器化部署及构建容器化机器学习流水线。然而,将模型部署到生产环境只是第一步,更重要的是确保其持续稳定运行并保持性能。为此,必须关注容器化AI模型的监控与治理。 监控和治理至关重要,因为AI模型在生产环境中面临数据漂移、概念漂移、模型退化和安全风险等挑战。全面的监控涵盖模型性能、数据质量、解释性、安全性和版本管理等方面。使用Prometheus和Grafana可有效监控性能指标,而遵循模型治理最佳实践(如建立治理框架、定期评估、持续改进和加强安全)则能进一步提升模型的可信度和可靠性。总之,容器化AI模型的监控与治理是确保其长期稳定运行的关键。
|
Prometheus 监控 Cloud Native
Prometheus中的Exporter详解
【10月更文挑战第25天】Prometheus Exporter分为直接采集(如cAdvisor, Kubernetes)和间接采集(如Node Exporter)两类。
|
Prometheus 监控 Cloud Native
Grafana 入门指南:快速上手监控仪表盘
【8月更文第29天】Grafana 是一款开源的数据可视化和监控工具,它允许用户轻松地创建美观的仪表盘和图表,以便更好地理解和监控数据。无论您是需要监控系统性能指标、应用程序日志还是业务关键指标,Grafana 都能提供灵活而强大的解决方案。本指南将带领您快速上手 Grafana,包括安装、配置以及创建第一个监控面板。
4047 2
|
Prometheus 监控 Cloud Native
prometheus学习笔记之Grafana安装与配置
prometheus学习笔记之Grafana安装与配置
3670 2
|
Prometheus Cloud Native Java
OpenTelemetry: 经得起考验的工具
OpenTelemetry: 经得起考验的工具
2734 2
|
监控 Oracle 关系型数据库
性能监控之Telegraf+InfluxDB+Grafana+Python实现Oracle实时监控
【6月更文挑战14天】性能监控之Telegraf+InfluxDB+Grafana+Python实现Oracle实时监控
527 2