Python prometheus_client使用方式
#!/usr/bin/env python
# -*- coding: utf8 -*-
import socket,re
from prometheus_client import generate_latest, Gauge,Info
from prometheus_client.core import CollectorRegistry
from psutil import virtual_memory
from psutil import cpu_times
def check_port(ip, port):
'''socket检测端口连通性'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
try:
s.connect((ip, int(port)))
s.shutdown(2)
return True
except:
return False
REGISTRY = CollectorRegistry(auto_describe=False)
allportdata = [{'ip':'xxx.xxx.xxx.xxx','port':22},{'ip':'yyy.yyy.yyy.yyy','port':22},{'ip':'zzz.zzz.zzz.zzz','port':22}]
mem_percent = Gauge(
"system_memory_percent",
"Total system memory percent.",
registry=REGISTRY)
cpu_per = Gauge(
"system_cpu_percent",
"Total system cpu percent.",
registry=REGISTRY)
mem_percent.set(virtual_memory().percent)
cpu_per.set(cpu_times().system)
METRIC_NAME_RE = re.compile(r'^[a-zA-Z_:][a-zA-Z0-9_:]*$')
name = 'ip_port_conn_status'
documentation = "IP PORT SOCKET CONNECT STATUS."
portcheck = Gauge(name=name, documentation=documentation, labelnames=('ip', 'port'), registry=REGISTRY)
for i in allportdata:
status = check_port(i['ip'], i['port'])
portcheck.labels(i['ip'], i['port']).inc(status)
result = generate_latest(REGISTRY).decode()
print(result)
Python prometheus-client 安装
pip install prometheus-client
Python封装
# encoding: utf-8
from prometheus_client import Counter, Gauge, Summary
from prometheus_client.core import CollectorRegistry
from prometheus_client.exposition import choose_encoder
class Monitor:
def __init__(self):
# 注册收集器&最大耗时map
self.collector_registry = CollectorRegistry(auto_describe=False)
self.request_time_max_map = {}
# 接口调用summary统计
self.http_request_summary = Summary(name="http_server_requests_seconds",
documentation="Num of request time summary",
labelnames=("method", "code", "uri"),
registry=self.collector_registry)
# 接口最大耗时统计
self.http_request_max_cost = Gauge(name="http_server_requests_seconds_max",
documentation="Number of request max cost",
labelnames=("method", "code", "uri"),
registry=self.collector_registry)
# 请求失败次数统计
self.http_request_fail_count = Counter(name="http_server_requests_error",
documentation="Times of request fail in total",
labelnames=("method", "code", "uri"),
registry=self.collector_registry)
# 模型预测耗时统计
self.http_request_predict_cost = Counter(name="http_server_requests_seconds_predict",
documentation="Seconds of prediction cost in total",
labelnames=("method", "code", "uri"),
registry=self.collector_registry)
# 图片下载耗时统计
self.http_request_download_cost = Counter(name="http_server_requests_seconds_download",
documentation="Seconds of download cost in total",
labelnames=("method", "code", "uri"),
registry=self.collector_registry)
# 获取/metrics结果
def get_prometheus_metrics_info(self, handler):
encoder, content_type = choose_encoder(handler.request.headers.get('accept'))
handler.set_header("Content-Type", content_type)
handler.write(encoder(self.collector_registry))
self.reset_request_time_max_map()
# summary统计
def set_prometheus_request_summary(self, handler):
self.http_request_summary.labels(handler.request.method, handler.get_status(), handler.request.path).observe(handler.request.request_time())
self.set_prometheus_request_max_cost(handler)
# 自定义summary统计
def set_prometheus_request_summary_customize(self, method, status, path, cost_time):
self.http_request_summary.labels(method, status, path).observe(cost_time)
self.set_prometheus_request_max_cost_customize(method, status, path, cost_time)
# 失败统计
def set_prometheus_request_fail_count(self, handler, amount=1.0):
self.http_request_fail_count.labels(handler.request.method, handler.get_status(), handler.request.path).inc(amount)
# 自定义失败统计
def set_prometheus_request_fail_count_customize(self, method, status, path, amount=1.0):
self.http_request_fail_count.labels(method, status, path).inc(amount)
# 最大耗时统计
def set_prometheus_request_max_cost(self, handler):
requset_cost = handler.request.request_time()
if self.check_request_time_max_map(handler.request.path, requset_cost):
self.http_request_max_cost.labels(handler.request.method, handler.get_status(), handler.request.path).set(requset_cost)
self.request_time_max_map[handler.request.path] = requset_cost
# 自定义最大耗时统计
def set_prometheus_request_max_cost_customize(self, method, status, path, cost_time):
if self.check_request_time_max_map(path, cost_time):
self.http_request_max_cost.labels(method, status, path).set(cost_time)
self.request_time_max_map[path] = cost_time
# 预测耗时统计
def set_prometheus_request_predict_cost(self, handler, amount=1.0):
self.http_request_predict_cost.labels(handler.request.method, handler.get_status(), handler.request.path).inc(amount)
# 自定义预测耗时统计
def set_prometheus_request_predict_cost_customize(self, method, status, path, cost_time):
self.http_request_predict_cost.labels(method, status, path).inc(cost_time)
# 下载耗时统计
def set_prometheus_request_download_cost(self, handler, amount=1.0):
self.http_request_download_cost.labels(handler.request.method, handler.get_status(), handler.request.path).inc(amount)
# 自定义下载耗时统计
def set_prometheus_request_download_cost_customize(self, method, status, path, cost_time):
self.http_request_download_cost.labels(method, status, path).inc(cost_time)
# 校验是否赋值最大耗时map
def check_request_time_max_map(self, uri, cost):
if uri not in self.request_time_max_map:
return True
if self.request_time_max_map[uri] < cost:
return True
return False
# 重置最大耗时map
def reset_request_time_max_map(self):
for key in self.request_time_max_map:
self.request_time_max_map[key] = 0.0
调用
import tornado
import tornado.ioloop
import tornado.web
import tornado.gen
from datetime import datetime
from tools.monitor import Monitor
global g_monitor
class ClassifierHandler(tornado.web.RequestHandler):
def post(self):
# TODO Something you need
# work....
# 统计Summary,包括请求次数和每次耗时
g_monitor.set_prometheus_request_summary(self)
self.write("OK")
class PingHandler(tornado.web.RequestHandler):
def head(self):
print('INFO', datetime.now(), "/ping Head.")
g_monitor.set_prometheus_request_summary(self)
self.write("OK")
def get(self):
print('INFO', datetime.now(), "/ping Get.")
g_monitor.set_prometheus_request_summary(self)
self.write("OK")
class MetricsHandler(tornado.web.RequestHandler):
def get(self):
print('INFO', datetime.now(), "/metrics Get.")
g_monitor.set_prometheus_request_summary(self)
# 通过Metrics接口返回统计结果
g_monitor.get_prometheus_metrics_info(self)
def make_app():
return tornado.web.Application([
(r"/ping?", PingHandler),
(r"/metrics?", MetricsHandler),
(r"/work?", ClassifierHandler)
])
if __name__ == "__main__":
g_monitor = Monitor()
app = make_app()
app.listen(port)
tornado.ioloop.IOLoop.current().start()
Metrics返回结果实例

Python prometheus_client使用方式的更多相关文章
- [修]python普通继承方式和super继承方式
[转]python普通继承方式和super继承方式 原文出自:http://www.360doc.com/content/13/0306/15/9934052_269664772.shtml 原文的错 ...
- 【转】python 退出程序的方式
[转]python 退出程序的方式 python程序退出方式[sys.exit() os._exit() os.kill() os.popen(...)] 知乎说明 http://www.zhihu. ...
- 理解 Python 的执行方式,与字节码 bytecode 玩耍 (上)
这里有个博客讲 Python 内部机制,已经有一些中文翻译. 可能因为我用的Python 3.5,例子跑起来有些不一样. 此外,我又查了其他一些参考资料,总结如下: Python 的执行方式 先看一个 ...
- 理解 Python 的执行方式,与字节码 bytecode 玩耍 (下)
上次写到,Python 的执行方式是把代码编译成bytecode(字节码)指令,然后由虚拟机来执行这些 bytecode 而 bytecode 长成这个样子: b'|\x00\x00d\x01\x0 ...
- [Spark][python]以DataFrame方式打开Json文件的例子
[Spark][python]以DataFrame方式打开Json文件的例子: [training@localhost ~]$ cat people.json{"name":&qu ...
- python 退出程序的方式
python程序退出方式[sys.exit() os._exit() os.kill() os.popen(...)] 知乎说明 http://www.zhihu.com/question/21187 ...
- Python模块调用方式详解
Python模块调用方式详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其 ...
- python通过get方式,post方式发送http请求和接收http响应-urllib urllib2
python通过get方式,post方式发送http请求和接收http响应-- import urllib模块,urllib2模块, httplib模块 http://blog.163.com/xyc ...
- 大华摄像头报警接口中图片加密,python调用c++方式实现解密
项目中,大华摄像头的报警信息,里面有图片地址,需要1天内取下来,保持留痕 可惜,图片下载后,加密了,大华提供了android,ios,c++例子,没有提供java解密例子 没办法,只好先用c++例子简 ...
- [原]Python Web部署方式总结
不要让服务器裸奔 学过PHP的都了解,php的正式环境部署非常简单,改几个文件就OK,用FastCgi方式也是分分钟的事情.相比起来,Python在web应用上的部署就繁杂的多,主要是工具繁多,主流服 ...
随机推荐
- docker network macvlan
ref: Docker 网络模型之 macvlan 详解,图解,实验完整 网卡也能虚拟化?网卡虚拟化技术 macvlan 详解 docker和macvlan与host互通
- 爬虫案例1-爬取图片的三种方式之一:selenium篇(2)
@ 目录 前言 selenium简介 实战 共勉 ps 博客 前言 继使用requests库爬取图片后,本文使用python第三方库selenium来进行图片的爬取,后续也会使用同样是自动化测试工具D ...
- Excel 国产化替换新方案
前言 在当前数字化转型和信创(信息技术应用创新)战略背景下,企业对于安全性.自主可控性和高效办公工具的需求日益增加.作为一款国产自主研发的高性能表格控件,SpreadJS 正成为替换 Excel 的最 ...
- x64汇编——汇编指令
汇编指令 mov dest, src mov move的简称 将src的内容赋值给dest,类似于dest = src [地址值] 中扩号 [ ]里面放的都是内存地址 一个变量的地址值,是它所有字节地 ...
- [OI] 整体二分
整体二分可以理解成普通二分改版,其实并没有改多少,并且一般对 check() 函数的复杂度要求更宽松 先来看一道经典题目:求区间排名 给一个数列,若干组询问 \((l,r,k)\),求 \([l,r] ...
- 离线安装MySQL
离线安装mysql [下载地址](MySQL :: Download MySQL Community Server) 解压后依次执行如下命令 rpm -ivh mysql-community-comm ...
- CF102411 ICPC 2019-2020 North-Western Russia Regional Contest题解
A Accurate Movement 签到 M Managing Difficulties 签到 B Bad Treap 已知\(y=\sin(x)\),要求给出数组\(a[n]\),满足\(\fo ...
- jenkins 配置flyway报错No value provided for placeholder expressions: ${name}
业务场景:使用flyway将一个数据库的变更同步到另一个数据库,数据同步到一半的时候报错 No value provided for placeholder expressions: ${name}. ...
- USACO 2023 December Contest, Gold
Problem 1. Flight Routes 设原图的邻接矩阵为 \(e\),考虑它给我们的矩阵是什么东西. 设 \(d_{i, j}\) 表示 \(i\) 到 \(j\) 的路径数的奇偶性,那么 ...
- Docker高阶篇(一)
本篇章主要为工作实践过程中对高端应用的处理和把控 1.Docker复杂安装 mysql的主从复制 https://www.bilibili.com/video/BV1gr4y1U7CY?p=41&am ...