• 欢迎来到小爱博客,一个分享互联网IT技术的网站,喜欢就收藏吧!

使用Python和Flask编写Prometheus监控

flask 小爱 3个月前 (08-05) 49次浏览 已收录 0个评论 扫描二维码

Installation

pip install flask
pip install prometheus_client

Metrics

Prometheus提供4种类型Metrics:CounterGaugeSummaryHistogram

Counter

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

  1. import prometheus_client
  2. from prometheus_client import Counter
  3. from prometheus_client.core import CollectorRegistry
  4. from flask import Response, Flask
  5. app = Flask(__name__)
  6. requests_total = Counter("request_count", "Total request cout of the host")
  7. @app.route("/metrics")
  8. def requests_count():
  9. requests_total.inc()
  10. # requests_total.inc(2)
  11. return Response(prometheus_client.generate_latest(requests_total),
  12. mimetype="text/plain")
  13. @app.route('/')
  14. def index():
  15. requests_total.inc()
  16. return "Hello World"
  17. if __name__ == "__main__":
  18. app.run(host="0.0.0.0")

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

  1. # HELP request_count Total request cout of the host
  2. # TYPE request_count counter
  3. request_count 3.0

Gauge

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

  1. import random
  2. import prometheus_client
  3. from prometheus_client import Gauge
  4. from flask import Response, Flask
  5. app = Flask(__name__)
  6. random_value = Gauge("random_value", "Random value of the request")
  7. @app.route("/metrics")
  8. def r_value():
  9. random_value.set(random.randint(0, 10))
  10. return Response(prometheus_client.generate_latest(random_value),
  11. mimetype="text/plain")
  12. if __name__ == "__main__":
  13. app.run(host="0.0.0.0")

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

  1. # HELP random_value Random value of the request
  2. # TYPE random_value gauge
  3. random_value 3.0

Summary/Histogram

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

PLUS

LABELS

使用labels来区分metric的特征

  1. from prometheus_client import Counter
  2. c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip'])
  3. c.labels('get', '127.0.0.1').inc()
  4. c.labels('post', '192.168.0.1').inc(3)
  5. c.labels(method="get", clientip="192.168.0.1").inc()

REGISTRY

  1. from prometheus_client import Counter, Gauge
  2. from prometheus_client.core import CollectorRegistry
  3. REGISTRY = CollectorRegistry(auto_describe=False)
  4. requests_total = Counter("request_count", "Total request cout of the host", registry=REGISTRY)
  5. random_value = Gauge("random_value", "Random value of the request", registry=REGISTRY)

小爱博客 , 版权所有
转载请注明原文链接:使用Python和Flask编写Prometheus监控
喜欢 (0)
【你的支持, 我的动力】
分享 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址