一、背景说明
目前监控数据库服务安全的服务存在本身服务不受监控的问题,根据调研,目前技术社区对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