使用Python编写Prometheus监控的方法


Posted in Python onOctober 15, 2018

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

使用Python和Flask编写Prometheus监控

Installation

pip install flask
pip install prometheus_client

Metrics

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

Counter

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

import prometheus_client
from prometheus_client import Counter
from prometheus_client.core import CollectorRegistry
from flask import Response, Flask
app = 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 counter
request_count 3.0

Gauge

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")
@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 gauge
random_value 3.0

Summary/Histogram

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

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()

使用Python和asyncio编写Prometheus监控

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)
import prometheus_client
from prometheus_client import Counter,Gauge
from prometheus_client.core import CollectorRegistry
from aiohttp import web
import aiohttp
import asyncio
import uvloop
import random,logging,time,datetime
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
routes = web.RouteTableDef()
# metrics包含
requests_total = Counter("request_count", "Total request cout of the host") # 数值只增
random_value = Gauge("random_value", "Random value of the request") # 数值可大可小
@routes.get('/metrics')
async def metrics(request):
  requests_total.inc()   # 计数器自增
  # requests_total.inc(2)
  data = prometheus_client.generate_latest(requests_total)
  return web.Response(body = data,content_type="text/plain")  # 将计数器的值返回
@routes.get("/metrics2")
async def metrics2(request):
  random_value.set(random.randint(0, 10))  # 设置值任意值,但是一定要为 整数或者浮点数
  return web.Response(body = prometheus_client.generate_latest(random_value),content_type="text/plain")  # 将值返回
@routes.get('/')
async def hello(request):
  return web.Response(text="Hello, world")
# 使用labels来区分metric的特征
c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip']) # 添加lable的key,
c.labels('get', '127.0.0.1').inc()    #为不同的label进行统计
c.labels('post', '192.168.0.1').inc(3)   #为不同的label进行统计
c.labels(method="get", clientip="192.168.0.1").inc()  #为不同的label进行统计
g = Gauge('my_inprogress_requests', 'Description of gauge',['mylabelname'])
g.labels(mylabelname='str').set(3.6)  #value自己定义,但是一定要为 整数或者浮点数
if __name__ == '__main__':
  logging.info('server start:%s'% datetime.datetime.now())
  app = web.Application(client_max_size=int(2)*1024**2)  # 创建app,设置最大接收图片大小为2M
  app.add_routes(routes)   # 添加路由映射
  web.run_app(app,host='0.0.0.0',port=2222)  # 启动app
  logging.info('server close:%s'% datetime.datetime.now())

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
python的类变量和成员变量用法实例教程
Aug 25 Python
Python解析网页源代码中的115网盘链接实例
Sep 30 Python
Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
Jul 27 Python
Python实现基本线性数据结构
Aug 22 Python
python实现多层感知器
Jan 18 Python
在Python中通过getattr获取对象引用的方法
Jan 21 Python
Python中的元组介绍
Jan 28 Python
Python调用Windows API函数编写录音机和音乐播放器功能
Jan 05 Python
python GUI库图形界面开发之PyQt5信号与槽机制、自定义信号基础介绍
Feb 25 Python
python 中的命名空间,你真的了解吗?
Aug 19 Python
详解numpy1.19.4与python3.9版本冲突解决
Dec 15 Python
python数据分析之单因素分析线性拟合及地理编码
Jun 25 Python
python取数作为临时极大值(极小值)的方法
Oct 15 #Python
Python文件监听工具pyinotify与watchdog实例
Oct 15 #Python
Python并行分布式框架Celery详解
Oct 15 #Python
对Python 内建函数和保留字详解
Oct 15 #Python
Python 比较文本相似性的方法(difflib,Levenshtein)
Oct 15 #Python
便捷提取python导入包的属性方法
Oct 15 #Python
Django安装配置mysql的方法步骤
Oct 15 #Python
You might like
加强版phplib的DB类
2008/03/31 PHP
session在PHP大型web应用中的使用
2011/06/25 PHP
又一个PHP实现的冒泡排序算法分享
2014/08/21 PHP
腾讯CMEM的PHP扩展编译安装方法
2015/09/25 PHP
PHP浮点比较大小的方法
2016/02/14 PHP
Windows2003下php5.4安装配置教程(Apache2.4)
2016/06/30 PHP
解决Laravel5.2 Auth认证退出失效的问题
2019/10/14 PHP
贴一个在Mozilla中常用的Javascript代码
2007/01/09 Javascript
用window.location.href实现刷新另个框架页面
2007/03/07 Javascript
深入理解JavaScript系列(4) 立即调用的函数表达式
2012/01/15 Javascript
jquery结婚电子请柬特效源码分享
2015/08/21 Javascript
基于JavaScript实现在新的tab页打开url
2016/08/04 Javascript
javascript 判断页面访问方式电脑或者移动端
2016/09/19 Javascript
深入理解angular2启动项目步骤
2017/07/15 Javascript
JS设置随机出现2个数字的实例代码
2017/07/19 Javascript
Vue 多层组件嵌套二种实现方式(测试实例)
2017/09/08 Javascript
微信小程序 上传头像的实例详解
2017/10/27 Javascript
JavaScript数组特性与实践应用深入详解
2018/12/30 Javascript
React实现轮播效果
2020/08/25 Javascript
[45:18]2018DOTA2亚洲邀请赛 4.3 突围赛 Optic vs iG 第一场
2018/04/04 DOTA
[02:29]大剑、皮鞭、女装,这届DOTA2勇士令状里都有
2020/07/17 DOTA
python 移除字符串尾部的数字方法
2018/07/17 Python
python版本单链表实现代码
2018/09/28 Python
django 解决model中类写不到数据库中,数据库无此字段的问题
2020/05/20 Python
一款利用html5和css3动画排列人物头像的实例演示
2014/12/05 HTML / CSS
朗仕(Lab series)英国官网:雅诗兰黛集团男士专属护肤品牌
2017/11/28 全球购物
Urban Outfitters德国官网:美国跨国生活方式零售公司
2018/05/21 全球购物
我未来的职业规划范文
2014/01/11 职场文书
事业单位鉴定材料
2014/05/25 职场文书
销售队伍口号
2014/06/11 职场文书
党员学习中共十八大思想报告
2014/09/12 职场文书
毕业论文答辩开场白
2015/05/27 职场文书
少先队大队委竞选口号
2015/12/25 职场文书
2016党员学习《反对自由主义》心得体会
2016/01/22 职场文书
2016计划生育先进个人事迹材料
2016/02/29 职场文书
MySQL中utf8mb4排序规则示例
2021/08/02 MySQL