广告
返回顶部
首页 > 资讯 > 后端开发 > Python >详解Pythonprometheus_client使用方式
  • 785
分享到

详解Pythonprometheus_client使用方式

2024-04-02 19:04:59 785人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

背景说明 服务部署在阿里云的k8s上,配置了基于prometheus的Grafana监控。原本用的是自定义的Metrics接口统计,上报一些字段,后面发现Prometheus自带的监

背景说明

服务部署在阿里云k8s上,配置了基于prometheus的Grafana监控。原本用的是自定义的Metrics接口统计,上报一些字段,后面发现Prometheus自带的监控非常全面好用,适合直接抓取统计,所以做了一些改变。

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返回结果实例

Metrics返回结果截图

 到此这篇关于详解Python prometheus_client使用方式的文章就介绍到这了,更多相关Python prometheus_client内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 详解Pythonprometheus_client使用方式

本文链接: https://www.lsjlt.com/news/138523.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 详解Pythonprometheus_client使用方式
    背景说明 服务部署在阿里云的K8s上,配置了基于Prometheus的Grafana监控。原本用的是自定义的Metrics接口统计,上报一些字段,后面发现Prometheus自带的监...
    99+
    2022-11-13
  • Go error的使用方式详解
    目录概述error使用方式1.直接判等2.组合error接口,构建更强大的error接口3.Errno模式4.Go1.13的Wrap模式5. Go版本低时的链式error概述 ...
    99+
    2022-06-07
    GO error
  • Javasynchronized与CAS使用方式详解
    目录引言synchronizedsynchronized的三种使用方式synchronized的底层原理JDK1.6对synchronized的优化synchronized的等待唤醒...
    99+
    2023-01-16
    Java CAS Java synchronized
  • mysql中json的使用方式详解
    目录一、插入json数据的方式有两种二、查询 JSON 中字段的数据三、JSON字段的条件搜索mysql字段的数据类型支持json格式,可以直接存储json数组和json对象。 一、插入json数据的方式有两种 1、以普...
    99+
    2023-04-23
    mysql中json使用 mysql json
  • forEach循环里break使用方式详解
    目录一. 在forEach里使用break 会发生什么二. 为什么不能在forEach里使用break你真的了解break吗三.如何在forEach的循环里break?在forEac...
    99+
    2022-11-13
  • Python标准库time使用方式详解
    目录1、time库1.1、获取格林威治西部的夏令时地区的偏移秒数1.2、时间函数1.3、格式化时间、日期1.4、单调时钟1、time库 时间戳(timestamp)的方式:通常来说,...
    99+
    2022-11-11
  • C++内存管理详解使用方式
    目录c++中内存管理的方式new和delete操作符的使用方式operator new和operator delete函数new和delete的原理内部实现内置类型自定义类型c++中...
    99+
    2022-11-13
  • 详解Python列表解析式的使用方法
    目录列表解析式的优势如何在 Python 中创建列表循环map() 对象列表解析式哪种方法更有效高级解析式条件逻辑集合解析式字典解析式海象运算符什么时候不要使用解析式注意嵌套的解析式...
    99+
    2022-11-10
  • Go WaitGroup的使用方式及实例详解
    WaitGroup 是 Go 语言的一个并发控制机制,它可以用于等待一组 goroutine 的结束。WaitGroup 提供了三个...
    99+
    2023-10-12
    Go语言
  • 关于.NET6 Minimal API的使用方式详解
    目录前言使用方式几行代码构建Web程序更改监听地址日志操作基础环境配置主机相关设置默认容器替换中间件相关请求处理路由约束模型绑定绑定示例自定义绑定总结前言 随着.Net6的发布,微软...
    99+
    2022-11-12
  • docker启动rabbitmq以及使用方式详解
    目录搜索rabbitmq镜像下载镜像启动容器打印容器访问RabbitMQ Management编写生产者类消费者工作队列RabbitMqUtils工具类启动2个工作线程启动发送线程消...
    99+
    2022-11-13
    docker运行rabbitmq rabbitmq docker 启动rabbitmq命令
  • 详解Flutter中key的正确使用方式
    目录1、什么是key2、key的更新原理3、key的分类GlobalKeyLocalKey总结1、什么是key Widget中有个可选属性key,顾名思义,它是组件的标识符,当设置...
    99+
    2023-01-28
    Flutter key使用方式 Flutter key
  • Python Requests使用Cookie的几种方式详解
    目录前言一、通过headers参数使用二、通过cookies参数使用三、通过Session会话使用方式0:自动设置方式1:通过key设置方式2:通过set 方法设置方式3:通过 ad...
    99+
    2023-08-08
    python requests cookie python cookie
  • export default 和 export 的使用方式示例详解
    node中导入模块:var 名称 = require('模块标识符') node中向外暴露成员的形式:module.exports = {} 在ES6中,也通过规范的...
    99+
    2022-11-13
  • Maven使用方法详及方式详细介绍
    目录Maven简介1、软件开发中的阶段2、Maven能做什么3、没有使用maven怎么管理依赖4、什么是maven约定目录结构maven的使用方式POM文件坐标的概念依赖 depen...
    99+
    2022-11-13
    Maven使用方法 Maven方法 Maven使用方式
  • CentOS的详细使用方式
    这篇文章主要讲解了“CentOS的详细使用方式”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“CentOS的详细使用方式”吧!CentOS对大家来说已经很熟悉。什么是CentOS呢?CentO...
    99+
    2023-06-16
  • C语言中dlopen和dlsym的使用方式详解
    目录背景demo生产动态库调用dlopen总结背景 为了是不同的逻辑解耦,一般会把各个业务封装成动态库,然后主逻辑去调用各个插件。这里有个问题是,为什么以前我们都是通过include...
    99+
    2022-11-13
  • CentOS7.5使用mysql_multi方式安装MySQL5.7.28多实例(详解)
    因使用源码安装的MySQL5.7.28多实例,在导入数据库时会出现问题,所以重新研究使用mysql_multi的方法来管理多实例,经过测试环境验证之后,在各方面使用上特别在备份还原上,没有报MySQL5.7...
    99+
    2022-10-18
  • python中使用正则表达式的方法详解
    目录search(pattern, string, flags=0)findall(pattern, string, flags=0)sub(pattern, repl, strin...
    99+
    2022-11-13
  • C++中正则表达式的使用方法详解
    目录介绍1. C++ 中的正则表达式 (Regex)1.1 范围规范1.2 重复模式2. C++正则表达式的例子3. C++正则表达式中使用的函数模板3.1 regex_match(...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作