首页 > 编程 > Python > 正文

使用Python编写Prometheus监控的方法

2020-02-15 23:13:47
字体:
来源:转载
供稿:网友

要使用python编写Prometheus监控,需要你先开启Prometheus集群。可以参考//www.jb51.net/article/148895.htm 安装。在python中实现服务器端。在Prometheus中配置请求网址,Prometheus会定期向该网址发起申请获取你想要返回的数据。

使用Python和Flask编写Prometheus监控

Installation

pip install flaskpip install prometheus_client

Metrics

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

Counter

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

import prometheus_clientfrom prometheus_client import Counterfrom prometheus_client.core import CollectorRegistryfrom flask import Response, Flaskapp = Flask(__name__)requests_total = Counter("request_count", "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 "Hello World"if __name__ == "__main__":  app.run(host="0.0.0.0")

运行该脚本,访问youhost:5000/metrics

# HELP request_count Total request cout of the host# TYPE request_count counterrequest_count 3.0

Gauge

Gauge与Counter类似,唯一不同的是Gauge数值可以减少,常被用于温度、利用率等指标。

import randomimport prometheus_clientfrom prometheus_client import Gaugefrom flask import Response, Flaskapp = Flask(__name__)random_value = Gauge("random_value", "Random value of the request")@app.route("/metrics")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="0.0.0.0")

运行该脚本,访问youhost:5000/metrics

# HELP random_value Random value of the request# TYPE random_value gaugerandom_value 3.0

Summary/Histogram

Summary/Histogram概念比较复杂,一般exporter很难用到,暂且不说。

LABELS

使用labels来区分metric的特征

from prometheus_client import Counterc = 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()

使用Python和asyncio编写Prometheus监控

from prometheus_client import Counter, Gaugefrom prometheus_client.core import CollectorRegistryREGISTRY = 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)            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表