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应用上的部署就繁杂的多,主要是工具繁多,主流服 ...
随机推荐
- spark 中时间和日期 操作,怎么找到前几天后几天
1. timestamp 增加减少一个 time delta df.withColumn("added_hours",col("input_timestamp" ...
- python 浅拷贝与深拷贝
赋值引用 >>> a= {1:[1,2]}>>> b = a>>> b[2]=3>>> b {1: [1, 2], 2: 3} ...
- 单个48TB大小SQL Server数据库备份导致日志文件无法截断
单个48TB大小SQL Server数据库备份导致日志文件无法截断 SQL Server 版本:SQL Server 2019背景在一个48T大小的单数据库环境中,采用简单恢复模式,日志文件大小限制为 ...
- python脚本之requests库上传文件
一.前言 在学习的时候,发现有一个AWD的文件上传执行漏洞,突然想着批量对不同靶机进行操作并get_flag.思路简单,但是没构造 过文件上传的requests 的post请求的payload.便记录 ...
- 使用 Performance API 实现前端资源监控
1. Performance API 的用处 Performance API 是浏览器中内置的一组工具,用于测量和记录页面加载和执行过程中的各类性能指标.它的主要用处包括: 监控页面资源加载:跟踪页面 ...
- C++中对象的延迟构造
本文并不讨论"延迟初始化"或者是"懒加载的单例"那样的东西,本文要讨论的是分配某一类型所需的空间后不对类型进行构造(即对象的lifetime没有开始),更通俗点 ...
- Maven 依赖项管理&&依赖范围
依赖管理 使用坐标导入jar包 1.在pom.xml 中编写 <dependencies> 标签 2.在 <dependencies> 标签中使用 < ...
- 高通ADSP USB流程
在高通平台上,ADSP(Audio Digital Signal Processor,音频数字信号处理器)可以通过 USB 接口与主机进行数据传输,以下是大致的 ADSP USB 流程: 主机发起 U ...
- 2024年1月中国数据库排行榜: OPOT 组合续写贺新年,达梦、腾讯发力迎升势
2024年开局,墨天轮中国数据库流行度排行火热出炉,292个国产数据库齐聚榜单.整体来看,榜单前十整体变化不大,"O-P-O"格局稳固,前五位名次未发生变动.但新年伊始,各家数据库 ...
- Python 潮流周刊#72:Python 3.13.0 最终版已发布!(摘要)
本周刊由 Python猫 出品,精心筛选国内外的 250+ 信息源,为你挑选最值得分享的文章.教程.开源项目.软件工具.播客和视频.热门话题等内容.愿景:帮助所有读者精进 Python 技术,并增长职 ...