12.2 使用prometheus-sdk向pushgateway打点

本节重点介绍 :

  • 使用golang sdk打prometheus4种指标,推送到pushgateway
    • gauge、counter、histogram、summary的初始化
    • 4种类似的设置值的方法
    • 推送到pushgateway的方法
  • prometheus配置采集pushgateway,grafana上配大盘

golang-sdk

  • 项目地址 https://github.com/prometheus/client_golang

使用sdk打点并推送到pushgateway

首先导入包,初始化pusher 推送对象

import (
"github.com/prometheus/client_golang/prometheus/push"
)
var (// pusher对象pusher *push.Pusher
)

初始化4种数据metrics对象

	// 带标签的gaugeTestMetricGauge01 = prometheus.NewGaugeVec(prometheus.GaugeOpts{Name: "test_metric_gauge_01",Help: "gauge metic test 01",}, []string{"idc", "ip"})// 带标签的counterTestMetricCounter01 = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "test_metric_counter_01",Help: "gauge metic counter 01",}, []string{"path", "code"})// histogramhisStart        = 0.1histWidth       = 0.2TestHistogram01 = prometheus.NewHistogram(prometheus.HistogramOpts{Name:    "test_histogram_01",Help:    "RPC latency distributions.",// histogram 需要传入 bucket的start 和width参数Buckets: prometheus.LinearBuckets(hisStart, histWidth, 20),})// summaryTestSummary01 = prometheus.NewSummaryVec(prometheus.SummaryOpts{Name:       "test_summary_01",Help:       "RPC latency distributions.",// summary需要固定好最后的分位值结果Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},},[]string{"service"},)

编写初始化pusher对象和注册metrics的Init函数

func Init(url string, jobName string) {pusher = push.New(url, jobName)// collector 注册metricspusher.Collector(TestMetricGauge01)pusher.Collector(TestMetricCounter01)pusher.Collector(TestHistogram01)pusher.Collector(TestSummary01)}

编写设置gauge和counter值的函数 setValueGaugeAndCounter

  • counter 只能恒增,需要使用Add函数
// gauge和counter设置值的方法
func setValueGaugeAndCounter() {for {TestMetricGauge01.With(prometheus.Labels{"idc": "bj", "ip": "1.1"}).Set(float64(rand.Intn(100)))TestMetricCounter01.With(prometheus.Labels{"path": "/login", "code": "200"}).Add(float64(rand.Intn(100)))time.Sleep(5 * time.Second)}
}

编写设置histogram值的函数 setValueHistogram

  • histogram 使用Observe函数设置bucket的值
func setValueHistogram() {for {v := rand.NormFloat64()TestHistogram01.Observe(v)time.Sleep(100 * time.Millisecond)}
}

编写设置summary值的函数 setValueGaugeAndCounter

  • summary使用Observe设置值
// Summary设置值的方法
func setValueSummary() {for {v := rand.Float64()TestSummary01.WithLabelValues("uniform").Observe(v)time.Sleep(100 * time.Millisecond)}
}

编写推送到pushgateway的函数

func PushWork() {for {err := pusher.Push()if err != nil {fmt.Println("Could not push completion time to Pushgateway:", err)}time.Sleep(5 * time.Second)}}

main函数启动任务

  • 依次启动设置值的协程
  • 启动push的协程
func main() {rand.Seed(time.Now().UnixNano())Init("http://172.20.70.205:9091/", "my_job")go setValueGaugeAndCounter()go setValueHistogram()go setValueSummary()go PushWork()select {}
}

pushgateway中查看对应指标

  • 举例图片
  • image.png

将单个pushgateway加入prometheus采集job中

  - job_name: 'pushgateway'honor_timestamps: truescrape_interval: 15sscrape_timeout: 10smetrics_path: /metricsscheme: httpstatic_configs:- targets:- 172.20.70.205:9091- 172.20.70.215:9091

在prometheus查询相关指标

promql

  • histogram histogram_quantile(0.95, sum by(le) (rate(test_histogram_01_bucket[5m])))
  • image.png
  • summary test_summary_01
  • counter rate(test_metric_counter_01[1m])
  • image.png
  • gauge test_metric_gauge_01

在grafana上设置相关图表

举例图片

image.png

grafana json

{"annotations": {"list": [{"builtIn": 1,"datasource": "-- Grafana --","enable": true,"hide": true,"iconColor": "rgba(0, 211, 255, 1)","name": "Annotations & Alerts","type": "dashboard"}]},"editable": true,"gnetId": null,"graphTooltip": 0,"id": 11,"links": [],"panels": [{"aliasColors": {},"bars": false,"dashLength": 10,"dashes": false,"datasource": null,"fieldConfig": {"defaults": {},"overrides": []},"fill": 1,"fillGradient": 0,"gridPos": {"h": 9,"w": 12,"x": 0,"y": 0},"hiddenSeries": false,"id": 2,"legend": {"avg": false,"current": false,"max": false,"min": false,"show": true,"total": false,"values": false},"lines": true,"linewidth": 1,"nullPointMode": "null","options": {"alertThreshold": true},"percentage": false,"pluginVersion": "7.5.1","pointradius": 2,"points": false,"renderer": "flot","seriesOverrides": [],"spaceLength": 10,"stack": false,"steppedLine": false,"targets": [{"exemplar": true,"expr": "test_metric_gauge_01","interval": "","legendFormat": "","refId": "A"}],"thresholds": [],"timeFrom": null,"timeRegions": [],"timeShift": null,"title": "test_metric_gauge_01","tooltip": {"shared": true,"sort": 0,"value_type": "individual"},"type": "graph","xaxis": {"buckets": null,"mode": "time","name": null,"show": true,"values": []},"yaxes": [{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true},{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true}],"yaxis": {"align": false,"alignLevel": null}},{"aliasColors": {},"bars": false,"dashLength": 10,"dashes": false,"datasource": null,"fieldConfig": {"defaults": {},"overrides": []},"fill": 1,"fillGradient": 0,"gridPos": {"h": 9,"w": 12,"x": 12,"y": 0},"hiddenSeries": false,"id": 3,"legend": {"avg": false,"current": false,"max": false,"min": false,"show": true,"total": false,"values": false},"lines": true,"linewidth": 1,"nullPointMode": "null","options": {"alertThreshold": true},"percentage": false,"pluginVersion": "7.5.1","pointradius": 2,"points": false,"renderer": "flot","seriesOverrides": [],"spaceLength": 10,"stack": false,"steppedLine": false,"targets": [{"exemplar": true,"expr": "rate(test_metric_counter_01[1m])","interval": "","legendFormat": "","refId": "A"}],"thresholds": [],"timeFrom": null,"timeRegions": [],"timeShift": null,"title": "qps","tooltip": {"shared": true,"sort": 0,"value_type": "individual"},"type": "graph","xaxis": {"buckets": null,"mode": "time","name": null,"show": true,"values": []},"yaxes": [{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true},{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true}],"yaxis": {"align": false,"alignLevel": null}},{"aliasColors": {},"bars": false,"dashLength": 10,"dashes": false,"datasource": null,"fieldConfig": {"defaults": {},"overrides": []},"fill": 1,"fillGradient": 0,"gridPos": {"h": 9,"w": 12,"x": 0,"y": 9},"hiddenSeries": false,"id": 4,"legend": {"avg": false,"current": false,"max": false,"min": false,"show": true,"total": false,"values": false},"lines": true,"linewidth": 1,"nullPointMode": "null","options": {"alertThreshold": true},"percentage": false,"pluginVersion": "7.5.1","pointradius": 2,"points": false,"renderer": "flot","seriesOverrides": [],"spaceLength": 10,"stack": false,"steppedLine": false,"targets": [{"exemplar": true,"expr": "histogram_quantile(0.95, sum by(le) (rate(test_histogram_01_bucket[5m])))","interval": "","legendFormat": "","refId": "A"}],"thresholds": [],"timeFrom": null,"timeRegions": [],"timeShift": null,"title": "histogram 分位置","tooltip": {"shared": true,"sort": 0,"value_type": "individual"},"type": "graph","xaxis": {"buckets": null,"mode": "time","name": null,"show": true,"values": []},"yaxes": [{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true},{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true}],"yaxis": {"align": false,"alignLevel": null}},{"aliasColors": {},"bars": false,"dashLength": 10,"dashes": false,"datasource": null,"fieldConfig": {"defaults": {},"overrides": []},"fill": 1,"fillGradient": 0,"gridPos": {"h": 9,"w": 12,"x": 12,"y": 9},"hiddenSeries": false,"id": 5,"legend": {"avg": false,"current": false,"max": false,"min": false,"show": true,"total": false,"values": false},"lines": true,"linewidth": 1,"nullPointMode": "null","options": {"alertThreshold": true},"percentage": false,"pluginVersion": "7.5.1","pointradius": 2,"points": false,"renderer": "flot","seriesOverrides": [],"spaceLength": 10,"stack": false,"steppedLine": false,"targets": [{"exemplar": true,"expr": "test_summary_01","interval": "","legendFormat": "","refId": "A"}],"thresholds": [],"timeFrom": null,"timeRegions": [],"timeShift": null,"title": "summary 分位值","tooltip": {"shared": true,"sort": 0,"value_type": "individual"},"type": "graph","xaxis": {"buckets": null,"mode": "time","name": null,"show": true,"values": []},"yaxes": [{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true},{"format": "short","label": null,"logBase": 1,"max": null,"min": null,"show": true}],"yaxis": {"align": false,"alignLevel": null}}],"refresh": "10s","schemaVersion": 27,"style": "dark","tags": [],"templating": {"list": []},"time": {"from": "now-30m","to": "now"},"timepicker": {},"timezone": "","title": "自打点pushgatway指标","uid": "Kqdgmyn7k","version": 2
}

全量代码

package mainimport ("fmt""github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/push""math/rand""time"
)var (// 带标签的gaugeTestMetricGauge01 = prometheus.NewGaugeVec(prometheus.GaugeOpts{Name: "test_metric_gauge_01",Help: "gauge metic test 01",}, []string{"idc", "ip"})// 带标签的counterTestMetricCounter01 = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "test_metric_counter_01",Help: "gauge metic counter 01",}, []string{"path", "code"})// histogramhisStart        = 0.1histWidth       = 0.2TestHistogram01 = prometheus.NewHistogram(prometheus.HistogramOpts{Name:    "test_histogram_01",Help:    "RPC latency distributions.",Buckets: prometheus.LinearBuckets(hisStart, histWidth, 20),})// summaryTestSummary01 = prometheus.NewSummaryVec(prometheus.SummaryOpts{Name:       "test_summary_01",Help:       "RPC latency distributions.",Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},},[]string{"service"},)// pusher对象pusher *push.Pusher
)func Init(url string, jobName string) {pusher = push.New(url, jobName)// collector 注册metricspusher.Collector(TestMetricGauge01)pusher.Collector(TestMetricCounter01)pusher.Collector(TestHistogram01)pusher.Collector(TestSummary01)}// Summary设置值的方法
func setValueSummary() {for {v := rand.Float64()TestSummary01.WithLabelValues("uniform").Observe(v)time.Sleep(100 * time.Millisecond)}
}// gauge和counter设置值的方法
func setValueGaugeAndCounter() {for {TestMetricGauge01.With(prometheus.Labels{"idc": "bj", "ip": "1.1"}).Set(float64(rand.Intn(100)))TestMetricCounter01.With(prometheus.Labels{"path": "/login", "code": "200"}).Add(float64(rand.Intn(100)))time.Sleep(5 * time.Second)}
}func setValueHistogram() {for {v := rand.NormFloat64()TestHistogram01.Observe(v)time.Sleep(100 * time.Millisecond)}
}func PushWork() {for {err := pusher.Push()if err != nil {fmt.Println("Could not push completion time to Pushgateway:", err)}time.Sleep(5 * time.Second)}}
func main() {rand.Seed(time.Now().UnixNano())Init("http://172.20.70.205:9091/", "my_job")go setValueGaugeAndCounter()go setValueHistogram()go setValueSummary()go PushWork()select {}
}

本节重点总结 :

  • 使用golang sdk打prometheus4种指标,推送到pushgateway
    • gauge、counter、histogram、summary的初始化
    • 4种类似的设置值的方法
    • 推送到pushgateway的方法
  • prometheus配置采集pushgateway,grafana上配大盘

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/403857.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

系统架构设计师 - 软件工程(2)

软件工程 软件工程(13-22分)非常重要软件系统建模系统设计界面设计 ★★软件设计结构化设计 ★★面向对象设计 ★★★★★基本过程设计原则设计模式创建型模式:创建对象结构型模式:更大的结构行为型模式:交互及职责分配…

科三预约考试,为什么我场次排名在前,后面排名又变了

什么时候知道是否预约成功 系统确认考试预约结果的时间一般为考试前5-7个工作日,同时根据预约人数系统会自行判断提前1-2日或延长1-2日公示预约结果,学员至少考试前三天会收到预约成功短信通知。 如果预约失败了怎么办?会计入考试次数吗&am…

Java之线程篇一

目录 如何理解进程? 进程和线程的区别 线程的优点 线程的缺点 线程异常 线程用途 创建线程 方法一:继承Thread类,重写run() 观察线程 小结 方法二: 实现Runnable接口,重写run() 方法三:继承Threa…

【西安电子科技大学】2024年士兵计划考研信息总结!

西安电子科技大学 学校简介上方图片奖助学金下方图片研招网址https://gr.xidian.edu.cn/普通复试https://gr.xidian.edu.cn/info/1073/13301.htm士兵复试总分为各学科门类、各专业学位类别(领域)国家A类线,单科不限。士兵名额20报考说明无录取…

MES系统从哪几方面提升企业制造水平?

在当今这个快速变化的制造环境中,企业对于提升制造水平的追求从未停止。制造执行系统(MES)作为连接企业战略规划与车间实际操作的核心工具,其重要性日益凸显。盘古信息MES系统,凭借其独特的功能模块和创新的设计理念&a…

两种图像透明背景转特定颜色方法的比较

之前写过一篇博客,关于透明背景转换为特定颜色,当时使用了NumPy数组采用布尔索引转换的方式,这次我们把这种转换和常规的逐像素转换的方式进行比较,看那种方法效率更高。记得以前使用Matlab的时候,显然是矩阵布尔索引的…

基于SSM的体育馆预约管理系统---附源码84196

摘 要 体育馆作为一个重要的运动场所,需要进行预约管理以保证资源的合理利用和场馆秩序的维护。传统的人工预约管理方式存在效率低、容易出错等问题,因此,在互联网高速发展的当下,需要设计和实现一个基于SSM的体育馆预约管理系统&…

优思学院|六西格玛实施关键:如何整合定性与定量数据

在精益六西格玛的世界中,数据不仅是工具,更是推动变革和改进的关键力量。了解定性数据和定量数据的区别,可以为流程改进提供强大的见解和策略。 定性数据与定量数据的本质 首先,定性数据和定量数据是两种截然不同的概念。定性数据…

springboot+vue 初始

1.控制器 2.文件上传拦截器 #过滤规则 # 默认访问static下面的文件http://localhost:8009/4.jpeg, # 带上static-path-pattern/static/**后,http://localhost:8009/static/4.jpeg spring.mvc.static-path-pattern/static/**#静态资源位置 spring.web.res…

笔记分享: 香港中文大学CSCI5610高级数据结构——最邻近查询

文章目录 Approximate Nearest Neighbor Search \textbf{Approximate Nearest Neighbor Search} Approximate Nearest Neighbor Search 1. Doubling Dimension \textbf{1. Doubling Dimension} 1. Doubling Dimension 1.0. Intro \textbf{1.0. Intro} 1.0. Intro 1.1. Doubling…

webshell免杀--免杀入门

前言 欢迎来到我的博客 个人主页:北岭敲键盘的荒漠猫-CSDN博客 本文主要整理webshell免杀的一些基础思路 入门级,不是很深入,主要是整理相关概念 免杀对象 1.各类杀毒软件 类似360,火绒等,查杀己方webshell的软件。 2.各类流量…

Spring Boot和OCR构建车牌识别系统

​ 博客主页: 南来_北往 系列专栏:Spring Boot实战 OCR介绍 OCR(Optical Character Recognition)是光学字符识别技术的缩写,它能够将图像中的文本转换为机器可读和编辑的数字文本格式。这种技术广泛应用于数据输入、文档管理…

【名单】新一批DCMM贯标认证名单公布

​近日,DCMM官方平台发布通知公告,经对评估机构提交的380家企业贯标评估报告进行核查,均符合要求,现对名单进行公示,其中: 甲方受管理级(二级):276家 乙方受管理级(二级):96家 甲方…

LMDeploy 量化部署实践闯关任务

一、LMDeploy量化介绍 1.LMDeploy部署模型的优势 LMDeploy实现了高效的推理、可靠的量化、卓越的兼容性、便捷的服务以及有状态的推理。 相比于vllm具有领先的推理性能: LMDeploy也提供了大模型量化能力:主要包括KV Cache量化和模型权重量化。 LMDepl…

【python】python代码打包工具cx_Freeze的介绍、原理、用法及实战案例分析

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,…

AI工作流:低代码时代的革新者,重塑手机问答类应用生态

在这个数字化迅猛发展的时代,低代码技术正以惊人的速度改变着我们的生活方式。作为低代码人群的先锋,AI工作流技术正在以前所未有的方式,赋予非技术人群实现梦想的能力 🔥能用AI-低代码传送门:https://www.nyai.chat …

1. windows搭建Kafka教程

目录 1. 部署zookeeper 1.1 下载地址 1.3 修改zoo配置 1.4 启动zookeepe服务 02 部署kafka 2.1 下载组件包 2.2 解压安装包 2.3 修改配置 2.4 启动kafka服务端 1. 部署zookeeper 1.1 下载地址 下载地址: kafka/zookeeper 下载地址 (qq.com) 1.2 解压 (…

JS模块化总结 | CommonJS、ES6

BV13W42197jR 个人笔记 目录 JS模块化基础知识1. 概述1.1 什么是模块化1.2 为什么需要模块化? 2 模块化规范3 导入&导出4 CommonJS规范4.1 初步体验4.2 导出数据4.3 导入数据4.4 扩展理解4.5 浏览器端运行 5 ES6模块化规范5.1 初步体验5.2 Node中运行ES65.3 导出数据①分别…

一文掌握 Web 测试:功能、界面、兼容与安全的综合测试指南!

随着Web技术的不断演进,测试除了对应用的功能性、界面美观性、跨平台兼容性的基本要求外、安全性和性能的要求也逐步增高。因此,全面、系统的测试思维和策略成为了保证Web应用高质量的关键因素。本篇文章将从功能测试、界面测试、兼容性测试和安全测试四…

【数据结构】PTA 带头结点的链式表操作集 C语言

本题要求实现带头结点的链式表操作集。 函数接口定义: List MakeEmpty(); Position Find( List L, ElementType X ); bool Insert( List L, ElementType X, Position P ); bool Delete( List L, Position P ); 其中List结构定义如下: typedef struc…