Flask项目编写Prometheus监控

本文介绍了如何在Flask项目中集成Prometheus进行监控,包括Counter、Gauge、Summary、Histogram、Info、Enum、Labels和Registry的使用,并提供了一个简单的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、背景说明

目前监控数据库服务安全的服务存在本身服务不受监控的问题,根据调研,目前技术社区对Prometheus有较高评价,并且在k8s中的使用率高,目前已有完成的exporter能够监控k8s集群的各项服务。

二、概念介绍

Prometheus定义了4种不同的指标类型(metric type):Counter(计数器)、Gauge(仪表盘)、Histogram(直方图)、Summary(摘要)。

Counter:Counter类型的指标其工作方式和计数器一样,只增不减(除非系统发生重置)。

Gauge:与Counter不同,Gauge类型的指标侧重于反应系统的当前状态。因此这类指标的样本数据可增可减。

Histogram和Summary主用用于统计和分析样本的分布情况。

三、Flask项目示例

1.安装包

首先安装包

pip install prometheus_client
pip install flask
2. Counter
    常用于统计http_requests_total,处理任务量等,一般在定义Counter类型指标的名称时推荐使用_total作为后缀。
# vim pro_test.py
import random
import prometheus_client
from prometheus_client import Counter
from flask import Response, Flask
 
app = Flask(__name__)
 
requests_total = Counter("http_requests_total", "Total request cout of the host")
 
 
@app.route("/metrics")
def requests_count():
    requests_total.inc()
    return Response(prometheus_client.generate_latest(requests_total),
                    mimetype="text/plain")
 
 
@app.route('/')
def index():
    return "Hello World"
 
 
if __name__ == "__main__":
    app.run(host="0.0.0.0")
      运行项目 python pro_test.py 访问http://0.0.0.0:5000/metrics

获得结果

# HELP http_requests_total Total request cout of the host
# TYPE http_requests_total counter
http_requests_total 1.0
# HELP http_requests_created Total request cout of the host
# TYPE http_requests_created gauge
http_requests_created 1.597221423470301e+09
3.Gauge
     与Counter类似,唯一不同的是Gauge数值可以减少,常被用于温度、利用率等指标。
import random
import prometheus_client
from prometheus_client import Gauge
from flask import Response, Flask
 
app = Flask(__name__)
 
random_value = Gauge("random_value", "Random value of the request", registry=REGISTRY)
 
 
@app.route("/metrics")
def requests_count():
    random_value.set(random.randint(0, 10))
    return Response(prometheus_client.generate_latest(random_value),
                    mimetype="text/plain")
 
 
@app.route('/')
def index():
    return "Hello World"
 
 
if __name__ == "__main__":
    app.run(host="0.0.0.0")

运行项目 python pro_test.py 访问http://0.0.0.0:5000/metrics

获得结果

# HELP random_value Random value 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值