使用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 28 Python
编写Python爬虫抓取暴走漫画上gif图片的实例分享
Apr 20 Python
python字典键值对的添加和遍历方法
Sep 11 Python
python类的继承实例详解
Mar 30 Python
Django模板变量如何传递给外部js调用的方法小结
Jul 24 Python
Pandas之drop_duplicates:去除重复项方法
Apr 18 Python
python主线程捕获子线程的方法
Jun 17 Python
python中报错"json.decoder.JSONDecodeError: Expecting value:"的解决
Apr 29 Python
Django自带的加密算法及加密模块详解
Dec 03 Python
Python常用库大全及简要说明
Jan 17 Python
python xlsxwriter模块的使用
Dec 24 Python
matplotlib绘制多子图共享鼠标光标的方法示例
Jan 08 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
mac下使用brew配置环境的步骤分享
2011/05/23 PHP
那些年一起学习的PHP(二)
2012/03/21 PHP
php中用加号与用array_merge合并数组的区别深入分析
2013/06/03 PHP
JavaScript入门教程 Cookies
2009/01/31 Javascript
javascript fullscreen全屏实现代码
2009/04/09 Javascript
一个可绑定数据源的jQuery数据表格插件
2010/07/17 Javascript
javascript中的prototype属性实例分析说明
2010/08/09 Javascript
js setTimeout 参数传递使用介绍
2013/08/13 Javascript
eclipse如何忽略js文件报错(附图)
2013/10/30 Javascript
解析jquery中的ajax缓存问题
2013/12/19 Javascript
Javascript中的apply()方法浅析
2015/03/15 Javascript
JavaScript使用pop方法移除数组最后一个元素用法实例
2015/04/06 Javascript
jQuery+css3实现Ajax点击后动态删除功能的方法
2015/08/10 Javascript
Vue如何实现组件的源码解析
2017/06/08 Javascript
jQuery Ajax使用FormData上传文件和其他数据后端web.py获取
2017/06/11 jQuery
关于vue项目中搜索节流的实现代码
2019/09/17 Javascript
15分钟上手vue3.0(小结)
2020/05/20 Javascript
python中字典dict常用操作方法实例总结
2015/04/04 Python
python实现实时监控文件的方法
2016/08/26 Python
Python简单实现自动删除目录下空文件夹的方法
2017/08/29 Python
Python使用matplotlib的pie函数绘制饼状图功能示例
2018/01/08 Python
Windows下Python3.6安装第三方模块的方法
2018/11/22 Python
windows下Pycharm安装opencv的多种方法
2020/03/05 Python
深入解析HTML5 Canvas控制图形矩阵变换的方法
2016/03/24 HTML / CSS
字中字效果的实现【html5实例】
2016/05/03 HTML / CSS
巴黎卡诗美国官方网站:始于1964年的头发头皮护理专家
2017/07/10 全球购物
Skyscanner阿联酋:全球领先的旅游搜索平台
2017/11/25 全球购物
沃尔玛加拿大:Walmart.ca
2020/03/02 全球购物
放飞中国梦演讲稿
2014/04/23 职场文书
宣传口号大全
2014/06/16 职场文书
租车协议书范本2014
2014/11/17 职场文书
2014年企业党支部工作总结
2014/12/04 职场文书
工作态度恶劣检讨书
2015/05/06 职场文书
2015年秋季运动会加油稿
2015/07/22 职场文书
MySQL 十大常用字符串函数详解
2021/06/30 MySQL
ConditionalOnProperty配置swagger不生效问题及解决
2022/06/14 Java/Android