使用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正则表达式
Jan 15 Python
python结合shell查询google关键词排名的实现代码
Feb 27 Python
13个最常用的Python深度学习库介绍
Oct 28 Python
python截取两个单词之间的内容方法
Dec 25 Python
Python父目录、子目录的相互调用方法
Feb 16 Python
python中logging模块的一些简单用法的使用
Feb 22 Python
Python按钮的响应事件详解
Mar 04 Python
Python的几种主动结束程序方式
Nov 22 Python
浅谈tensorflow中张量的提取值和赋值
Jan 19 Python
python日期与时间戳的各种转换示例
Feb 12 Python
Python实现播放和录制声音的功能
Aug 12 Python
python判断all函数输出结果是否为true的方法
Dec 03 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
咖啡历史、消费和行业趋势
2021/03/03 咖啡文化
PHP实现MVC开发得最简单的方法――模型
2007/04/10 PHP
PHP CKEditor 上传图片实现代码
2009/11/06 PHP
thinkPHP框架中执行原生SQL语句的方法
2017/10/25 PHP
转换json格式的日期为Javascript对象的函数
2010/07/13 Javascript
JS获取html对象的几种方式介绍
2013/12/05 Javascript
jQuery简单实现两级下拉菜单效果代码
2015/09/15 Javascript
JavaScript判断按钮被点击的方法
2015/12/13 Javascript
javascript经典特效分享 手风琴、轮播图、图片滑动
2016/09/14 Javascript
Base64(二进制)图片编码解析及在各种浏览器的兼容性处理
2017/02/09 Javascript
jQuery判断邮箱格式对错实例代码讲解
2017/04/12 jQuery
vue实现a标签点击高亮方法
2018/03/17 Javascript
解决v-for中使用v-if或者v-bind:class失效的问题
2018/09/25 Javascript
vue将后台数据时间戳转换成日期格式
2019/07/31 Javascript
基于JS实现操作成功之后自动跳转页面
2020/09/25 Javascript
[06:07]DOTA2-DPC中国联赛 正赛 Ehome vs VG 选手采访
2021/03/11 DOTA
python编程羊车门问题代码示例
2017/10/25 Python
Python获取Redis所有Key以及内容的方法
2019/02/19 Python
python 并发编程 非阻塞IO模型原理解析
2019/08/20 Python
关于Python-faker的函数效果一览
2019/11/28 Python
Pycharm添加虚拟解释器报错问题解决方案
2020/10/13 Python
HTML5 CSS3新的WEB标准和浏览器支持
2009/07/16 HTML / CSS
波兰香水和化妆品购物网站:Notino.pl
2017/11/07 全球购物
俄罗斯的精英皮具:Wittchen
2018/01/29 全球购物
YesBabyOnline美国:全球性的在线婚纱礼服工厂
2018/05/05 全球购物
西班牙电子产品购物网站:Electronicamente
2018/07/26 全球购物
销售简历自我评价
2014/01/24 职场文书
教师党员公开承诺事项
2014/05/28 职场文书
厕所文明标语
2014/06/11 职场文书
开展读书活动总结
2014/06/30 职场文书
学校门卫岗位职责范本
2014/06/30 职场文书
班主任先进事迹材料
2014/12/17 职场文书
教师节随笔
2015/08/15 职场文书
旅游安全责任协议书
2016/03/22 职场文书
导游词之海南-南湾猴岛
2019/10/12 职场文书
nginx设置资源请求目录的方式详解
2022/05/30 Servers