全栈工程师开发手册 (作者:栾鹏)
架构系列文章


要使用python编写Prometheus监控,需要你先开启Prometheus集群。可以参考https://blog.csdn.net/luanpeng825485697/article/details/80905585 安装。在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, Flaskapp = Flask(__name__)requests_total = Counter("request_count", "Total request cout of the host")# 如果只返回一个metrics
@app.route("/metrics")
def requests_count():requests_total.inc()# requests_total.inc(2)return Response(prometheus_client.generate_latest(requests_total),mimetype="text/plain")# 如果返回多个metrics
#### 定义一个仓库,存放数据
REGISTRY = CollectorRegistry(auto_describe=False)
muxStatus = Gauge("mux_api_21","Api response stats is:",registry=REGISTRY)
manageStatus = Gauge("manage_api_21","Api response stats is:",registry=REGISTRY)#### 定义路由
@app.route("/metrics")
def ApiResponse():muxStatus.set(muxCode)manageStatus.set(manageCode)return Response(prometheus_client.generate_latest(REGISTRY),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, Flaskapp = 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很难用到,暂且不说。

PLUS

LABELS

使用labels来区分metric的特征

from prometheus_client import Counterc = 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()

REGISTRY

#使用Python和asyncio编写Prometheus监控

from prometheus_client import Counter, Gauge
from prometheus_client.core import CollectorRegistryREGISTRY = 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")  # 数值可大可小# 如果返回一个metrics
@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")   # 将计数器的值返回# 如果返回多个metrics
参考flask中的写法@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,设置最大接收图片大小为2Mapp.add_routes(routes)     # 添加路由映射web.run_app(app,host='0.0.0.0',port=2222)   # 启动applogging.info('server close:%s'% datetime.datetime.now())

使用Python编写Prometheus监控metrics接口相关推荐

  1. 使用python编写一个完整的接口自动化用例

    使用python编写一个完整的接口自动化用例 以聚合数据的 查询天气接口为例: import requestsclass HttpRequests: def __init__(self,url, pa ...

  2. 用python编写daemon监控进程并自动恢复(附Shell版)

    因为hadoop集群中datanode是大量存在的,那么多机器,什么事都可能发生,最通常的大概就是进程挂掉了.所以为了省事,参考别人的代码写了这个监控进程的daemon.当然,稍加修改就可以用来监控别 ...

  3. prometheus监控redis(无metric接口)

    1,部署一个测试环境 [root@\ k8s-m-01~]# mkdir redis [root@\ k8s-m-01~]# cd redis/[root@\ k8s-m-01~/redis]# vi ...

  4. python编写接口初识一

    python编写接口这里用到的是他一个比较轻量级的框架 flask #!/usr/bin/python # -*- coding: UTF-8 -*- import flask,json server ...

  5. 开发笔记:Python脚本自动远程注册prometheus监控+注册jumpserver资产(tronado主机间通信)

    上一期:http://t.csdn.cn/541DY 安装完node_exporter后,需要在prometheus的配置文件中添加该节点才能使之被纳入prometheus的监控范围中.想要自动化该过 ...

  6. Prometheus监控系部署配置过程

    一.前言 Prometheus是由SoundCloud开发的开源监控报警系统和时序列数据库(TSDB),基于Go语言开发,是Google BorgMon监控系统的开源版本.Prometheus在201 ...

  7. 1. 初学prometheus监控

    文章目录 1. promethues 介绍 1.1 监控的分类 1.2 promethues 优点 1.3 promethues 使用场景 1.4 promethues 宏观架构图 2.部署服务端 2 ...

  8. 使用Prometheus监控Flink

    为什么选择Prometheus? 随着深入地了解Prometheus,你会发现一些非常好的功能: •服务发现使配置更加容易.Prometheus支持consul,etcd,kubernetes以及各家 ...

  9. Prometheus监控告警

    监控告警-Prometheus 第一章:概述 本章将介绍监控告警的一些基本概念. 1.1 什么是监控告警? 监控是什么? 说白了就是用一种形式去盯着.观察服务器,把服务器的各种行为表现都显示出来,用以 ...

最新文章

  1. 2018.08.27 lucky(模拟)
  2. 物理引擎demo (4) —— 力、关节和马达
  3. SpringBoot之CommandLineRunner,预先加载系统数据
  4. vim比vi做的一些改进
  5. java 内存泄漏 工具_Java剖析工具JProfiler入门使用教程:查找内存泄漏的方法
  6. html 将两个标签绑在一起,基本标签2
  7. php树形数据结构是什么,数据结构 之 树
  8. 小智机器人有初中课程吗_征战记大写的优秀!2020世界机器人大赛,看这些奖项收入囊中!...
  9. 任正非为什么向两千多年前的李冰父子学习?
  10. python实现天气功能查询
  11. 一台计算机多个屏幕,一台电脑多个显示器,屏幕远程控制
  12. 职位名称: Java技术经理
  13. excel2021 打印圆不圆
  14. 三菱modbusRTU通讯实例_三菱PLC的无线通讯实例
  15. 学习R语言编程——常用算法——导数与微积分的近似计算
  16. 【Html+CSS】3D旋转相册
  17. POJ1184-Smart typist
  18. 网站(基于区块链的版权保护系统)使用手册(未完成版)
  19. IOS 解决WKWebView加载本地html资源文件异常处理
  20. 【图像分割】直觉模糊C均值聚类的图像分割IFCM

热门文章

  1. 自动化所在语音识别研究中获进展
  2. 亚马逊新专利:Alexa可根据用户的语音识别疾病或抑郁
  3. 印象笔记电脑版使用技巧_苏江:打造你的第二大脑,印象笔记的5个超级使用技巧...
  4. LeetCode 111 二叉树的最小深度
  5. LeetCode 53最大子序和
  6. 2022牛客寒假算法基础集训营6 签到题5题(附基础集训营4-6签到题总结)
  7. 牛客竞赛,GDDU第十届文远知行杯新生程序设计竞赛,摸鱼记(BDEIKL题解,补G,ACFHJ)
  8. 【特别版】计算机哲学对学习生活借鉴的几个例子
  9. Word字体修改(罚抄,抄作业专用)
  10. 文件创建_LAMMPS data文件创建工具--moltemplate