使用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 30 Python
跟老齐学Python之Python文档
Oct 10 Python
Python在线运行代码助手
Jul 15 Python
Python对字符串实现去重操作的方法示例
Aug 11 Python
Python数据结构之顺序表的实现代码示例
Nov 15 Python
在CentOS6上安装Python2.7的解决方法
Jan 09 Python
1 行 Python 代码快速实现 FTP 服务器
Jan 25 Python
PyQt5固定窗口大小的方法
Jun 18 Python
Django shell调试models输出的SQL语句方法
Aug 29 Python
如何基于python测量代码运行时间
Dec 25 Python
PyQt5实现简单的计算器
May 30 Python
python退出循环的方法
Jun 18 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
第十三节 对象串行化 [13]
2006/10/09 PHP
解析百度搜索结果link?url=参数分析 (全)
2012/10/09 PHP
从PHP $_SERVER相关参数判断是否支持Rewrite模块
2013/09/26 PHP
ThinkPHP应用模式扩展详解
2014/07/16 PHP
PHP函数checkdnsrr用法详解(Windows平台用法)
2016/03/21 PHP
非常经典的PHP文件上传类分享
2016/05/15 PHP
xtree.js 代码
2007/03/13 Javascript
JQuery 浮动导航栏实现代码
2009/08/27 Javascript
Javascript 圆角div的实现代码
2009/10/15 Javascript
如何获取JQUERY AJAX返回的JSON结果集实现代码
2012/12/10 Javascript
js定时器怎么写?就是在特定时间执行某段程序
2013/10/11 Javascript
js利用事件的阻止冒泡实现点击空白模态框的隐藏
2014/01/24 Javascript
javascript实现页面内关键词高亮显示代码
2014/04/03 Javascript
jQuery实现复选框全选/取消全选/反选及获得选择的值
2014/06/12 Javascript
简介JavaScript中Boolean.toSource()方法的使用
2015/06/05 Javascript
JS实现新浪博客左侧的Blog管理菜单效果代码
2015/10/22 Javascript
原生 JS Ajax,GET和POST 请求实例代码
2016/06/08 Javascript
AngularJS  $on、$emit和$broadcast的使用
2016/09/05 Javascript
scroll事件实现监控滚动条并分页显示(zepto.js)
2016/12/18 Javascript
JavaScript实现简单的树形菜单效果
2017/06/23 Javascript
Vue三层嵌套路由的示例代码
2018/05/05 Javascript
vue中如何让子组件修改父组件数据
2018/06/14 Javascript
在vue中使用eslint,配合vscode的操作
2020/11/09 Javascript
[01:43]3.19DOTA2发布会 三代刀塔人第三代
2014/03/25 DOTA
python发送伪造的arp请求
2014/01/09 Python
python创建列表并给列表赋初始值的方法
2015/07/28 Python
Django的信号机制详解
2017/05/05 Python
Python的mysql数据库的更新如何实现
2017/07/31 Python
使用Keras预训练好的模型进行目标类别预测详解
2020/06/27 Python
Django contrib auth authenticate函数源码解析
2020/11/12 Python
adidas爱尔兰官方网站:阿迪达斯运动鞋和运动服
2019/11/01 全球购物
工作检讨书范文
2015/01/23 职场文书
二十年同学聚会致辞
2015/07/28 职场文书
幼儿园教师教育随笔
2015/08/14 职场文书
React中的Context应用场景分析
2021/06/11 Javascript
SQL Server使用PIVOT与unPIVOT实现行列转换
2022/05/25 SQL Server