使用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文件操作类操作实例详解
Jul 11 Python
基于Python Shell获取hostname和fqdn释疑
Jan 25 Python
python 将字符串转换成字典dict的各种方式总结
Mar 23 Python
Python中多个数组行合并及列合并的方法总结
Apr 12 Python
python更改已存在excel文件的方法
May 03 Python
python并发和异步编程实例
Nov 15 Python
5分钟 Pipenv 上手指南
Dec 20 Python
教你如何编写、保存与运行Python程序的方法
Jul 12 Python
Python解析命令行读取参数之argparse模块
Jul 26 Python
python Django编写接口并用Jmeter测试的方法
Jul 31 Python
使用python 的matplotlib 画轨道实例
Jan 19 Python
jupyter notebook oepncv 显示一张图像的实现
Apr 24 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
简单介绍下 PHP5 中引入的 MYSQLI的用途
2007/03/19 PHP
PHP 时间日期操作实战
2011/08/26 PHP
php将字符串转换成16进制的方法
2015/03/17 PHP
php源码分析之DZX1.5加密解密函数authcode用法
2015/06/17 PHP
php计算整个目录大小的方法
2015/06/19 PHP
仿新浪微博返回顶部的jquery实现代码
2012/10/01 Javascript
JavaScript中this的使用详解
2013/11/08 Javascript
jQuery插件实现文字无缝向上滚动效果代码
2016/02/25 Javascript
JavaScript简单下拉菜单特效
2016/09/13 Javascript
Vue非父子组件通信详解
2017/06/12 Javascript
ionic3 懒加载
2017/08/16 Javascript
js实现简单选项卡功能
2020/03/23 Javascript
Vue起步(无cli)的啊教程详解
2019/04/11 Javascript
微信小程序实现获取用户信息并存入数据库操作示例
2019/05/07 Javascript
vue实现数据控制视图的原理解析
2020/01/07 Javascript
[02:57]2014DOTA2国际邀请赛-观众采访
2014/07/19 DOTA
[39:53]完美世界DOTA2联赛PWL S2 LBZS vs Forest 第一场 11.19
2020/11/19 DOTA
Python通过递归遍历出集合中所有元素的方法
2015/02/25 Python
Python基于lxml模块解析html获取页面内所有叶子节点xpath路径功能示例
2018/05/16 Python
完美解决python中ndarray 默认用科学计数法显示的问题
2018/07/14 Python
python实现文件助手中查看微信撤回消息
2019/04/29 Python
Python chardet库识别编码原理解析
2020/02/18 Python
Django模板获取field的verbose_name实例
2020/05/19 Python
python链表类中获取元素实例方法
2021/02/23 Python
详解Django中的FBV和CBV对比分析
2021/03/01 Python
专门经营化妆刷的美国彩妆品牌:Sigma Beauty
2017/09/11 全球购物
SmartBuyGlasses德国:购买太阳镜和眼镜
2019/08/20 全球购物
英国自行车商店:AW Cycles
2021/02/24 全球购物
农业大学毕业生的个人自我评价
2013/10/11 职场文书
业务副厂长岗位职责
2014/01/03 职场文书
30岁生日感言
2014/01/25 职场文书
浪漫婚礼主持词
2014/03/14 职场文书
公司开业致辞
2015/07/29 职场文书
担保书怎么写 ?
2019/04/22 职场文书
Django使用echarts进行可视化展示的实践
2021/06/10 Python
python中的sys模块和os模块
2022/03/20 Python