使用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守护进程用法实例分析
Jun 04 Python
python中MethodType方法介绍与使用示例
Aug 03 Python
解决Python字典写入文件出行首行有空格的问题
Sep 27 Python
Python中摘要算法MD5,SHA1简介及应用实例代码
Jan 09 Python
python版微信跳一跳游戏辅助
Jan 11 Python
python操作xlsx文件的包openpyxl实例
May 03 Python
详解Python正则表达式re模块
Mar 19 Python
pyQt5实时刷新界面的示例
Jun 25 Python
python 利用pyttsx3文字转语音过程详解
Sep 25 Python
python中format函数如何使用
Jun 22 Python
python使用scapy模块实现ping扫描的过程详解
Jan 21 Python
python自动化操作之动态验证码、滑动验证码的降噪和识别
Aug 30 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
PHP的栏目导航程序
2006/10/09 PHP
PHP中一个控制字符串输出的函数
2006/10/09 PHP
PHP中SimpleXML函数用法分析
2014/11/26 PHP
Yii框架创建cronjob定时任务的方法分析
2017/05/23 PHP
js截取固定长度的中英文字符的简单实例
2013/11/22 Javascript
通过js来制作复选框的全选和不选效果
2014/05/22 Javascript
nodejs实现黑名单中间件设计
2014/06/17 NodeJs
JavaScript动态改变表格单元格内容的方法
2015/03/30 Javascript
javascript数组去重小结
2016/03/07 Javascript
javascript事件委托的用法及其好处简析
2016/04/04 Javascript
jQuery Mobile操作HTML5的常用函数总结
2016/05/17 Javascript
JS完成画圆圈的小球
2017/03/07 Javascript
Node.js安装配置图文教程
2017/05/10 Javascript
vue.js移动数组位置,同时更新视图的方法
2018/03/08 Javascript
Nodejs实现爬虫抓取数据实例解析
2018/07/05 NodeJs
Koa 使用小技巧(小结)
2018/10/22 Javascript
[01:38]完美世界DOTA2联赛PWL S3 集锦第四期
2020/12/21 DOTA
用python + hadoop streaming 分布式编程(一) -- 原理介绍,样例程序与本地调试
2014/07/14 Python
Pandas DataFrame 取一行数据会得到Series的方法
2018/11/10 Python
pyqt5之将textBrowser的内容写入txt文档的方法
2019/06/21 Python
Django中的cookie和session
2019/08/27 Python
详解Python 实现 ZeroMQ 的三种基本工作模式
2020/03/24 Python
keras实现基于孪生网络的图片相似度计算方式
2020/06/11 Python
Python dict的常用方法示例代码
2020/06/23 Python
Python爬取豆瓣数据实现过程解析
2020/10/27 Python
Django vue前后端分离整合过程解析
2020/11/20 Python
施华洛世奇英国官网:SWAROVSKI英国
2017/03/13 全球购物
英国最大的网上药品商店:Chemist Direct
2017/12/16 全球购物
澳大利亚体育和露营装备在线/实体零售商:Find Sports
2020/06/03 全球购物
怎么处理XML的中文问题
2015/03/26 面试题
社团招新策划书
2014/02/04 职场文书
婚礼主持结束词
2014/03/13 职场文书
小学教师师德演讲稿
2014/05/06 职场文书
小学英语课教学反思
2016/02/15 职场文书
2007年老电脑安装win11会怎么样? 网友实测win11在老电脑运行良好
2021/11/21 数码科技
解决MySQL Varchar 类型尾部空格的问题
2022/04/06 MySQL