当前位置: 首页 > news >正文

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上配大盘

相关文章:

12.2 使用prometheus-sdk向pushgateway打点

本节重点介绍 : 使用golang sdk打prometheus4种指标,推送到pushgateway gauge、counter、histogram、summary的初始化4种类似的设置值的方法推送到pushgateway的方法 prometheus配置采集pushgateway,grafana上配大盘 golang-sdk 项目地址 https://git…...

HTTPS 详解

HTTPS 是以安全为目标的 HTTP 通道,它在 HTTP 中加入 SSL 层以提高数据传输的安全性。HTTP 被用于在 Web 浏览器和网站服务器之间传递信息,但以明文形式发送内容,不提供任何方式的数据加密,如果攻击者截取了 Web 浏览器和网站服务…...

Microsoft Edge 使用方法与秘诀概览

目录 ​编辑引言 Microsoft Edge 功能与技巧概览 掌握这些设置技巧,让 Edge 浏览器的体验更干净 1. 使用阅读视图 2. 开启广告过滤 3. 管理扩展 4. 个性化新标签页 5. 使用网页截图 6. 清理浏览器缓存 7. 管理启动设置 8. 自定义地址栏建议 9. 使用内置笔…...

【视频】onvif、RTP、RTCP、SDP、RTSP、gb21818区别

ONVIF (Open Network Video Interface Forum): ONVIF是一个全球性的开放网络视频接口论坛,致力于发展基于IP网络的物联网设备的标准化。它提供了一个通用的标准接口,使不同厂商生产的网络视频产品能够互相兼容。 RTP (Real-time Transport Protocol): R…...

8-4 循环神经网络

对于 (8.4.2)中的函数 f f f,隐变量模型不是近似值。 毕竟 h t h_{t} ht​是可以仅仅存储到目前为止观察到的所有数据, 然而这样的操作可能会使计算和存储的代价都变得昂贵。 回想一下,我们在前面讨论过的具有隐藏单元的隐藏层。 值得注意的…...

Linux系统编程 --- 多线程

线程:是进程内的一个执行分支,线程的执行粒度,要比进程要细。 一、线程的概念 1、Linux中线程该如何理解 地址空间就是进程的资源窗口。 在一个程序里的一个执行路线就叫做线程(thread)。更准确的定义是&#xff1…...

Grafana中的rate与irate以及histogram

用法 rate rate函数用于计算一个时间序列在给定时间范围内的平均速率。它对每个数据点进行线性插值来计算速率,因此对于平滑和稳定的数据来说,rate是一个不错的选择。语法如下: rate(metric_name[time_range])metric_name: 指标名称。time…...

什么是网络安全态势感知

态势感知是一种基于环境的、动态、整体地洞悉安全风险的能力,是以安全大数据为基础,从全局视角提升对安全威胁的发现识别、理解分析、响应处置能力的一种方式、最终是为了决策与行动,是安全能力的落地 态势感知的重要性 随着网络与信息技术的…...

php 在app中唤起微信app进行支付,并处理回调通知

<?phpnamespace app\api\controller;use think\facade\Db; use think\facade\Log;class Wxzf {...

高效同步与处理:ADTF流服务在自动驾驶数采中的应用

目录 一、ADTF 流服务 1、流服务源&#xff08;Streaming Source&#xff09; 2、流服务汇&#xff08;Streaming Sink&#xff09; 二、数据链路 1、数据管道&#xff08;Data Pipe&#xff09; 2、子流&#xff08;Substreams&#xff09; 3、触发管道&#xff08;Tri…...

【Arduino】ATmega328PB 连接 LSM6DS3 姿态传感器,并读数据(不确定 ESP 系列是否可行,但大概率是可行的)

总览 1.初始化 ATmega328PB&#xff0c;默认大家已经完成了 328 的配置准备工作&#xff0c;已经直接能够向里面写入程序 2.接线&#xff0c;然后验证 mega328 的 I2C 设备接口能否扫描到 LSM6DS3 3.编写代码&#xff0c;上传&#xff0c;查看串口数据。完成。 一、初始化 AT…...

live2d + edge-tts 优雅的实现数字人讲话 ~

震惊&#xff01;live2d数字人竟开口说话 ~ 之前有想做数字人相关项目&#xff0c;查了一些方案。看了一些三方大厂的商用方案&#xff0c;口型有点尴尬&#xff0c;而且很多是采用视频流的方案&#xff0c;对流量的消耗很大。后来了解了live2d 技术&#xff0c;常在博客网页上…...

二进制安装php

下载php二进制包&#xff1a; 官网地址&#xff1a;https://www.php.net/releases/ PHP: Releaseshttps://www.php.net/releases/在里边可以选择自己要下载的包进行下载&#xff1b; 下载完成后进行解压&#xff1a; tar xvzf php-7.3.12.tar.gz 解压后 进入目录进行预编…...

旧版Pycharm支持的python版本记录

版权声明&#xff1a;本文为博主原创文章&#xff0c;如需转载请贴上原博文链接&#xff1a;旧版Pycharm支持的python版本记录-CSDN博客 前言&#xff1a;近期由于打算研究GitHub上一个开源量化交易平台开发框架&#xff0c;但是该框架是基于python3.10的版本开发&#xff0c;所…...

java实现七牛云内容审核功能,文本、图片和视频的内容审核(鉴黄、鉴暴恐、敏感人物)

目录 1、七牛云内容审核介绍 2、查看内容审核官方文档 2.1、文本内容审核 2.1.1、文本内容审核的请求示例 2.1.2、文本内容审核的返回示例 2.2、图片内容审核 2.2.1、请求参数 2.2.2、返回参数 2.3、视频内容审核 3、代码实现 3.1、前期代码准备 3.2、文本内容审核…...

C++面试基础系列-struct

系列文章目录 文章目录 系列文章目录C面试基础系列-struct1.C中struct2.C中struct2.1.同名函数2.2.typedef定义结构体别名2.3.继承 3.总结3.1.C和C中的Struct区别 4.struct字节对齐5.struct与const 关于作者 C面试基础系列-struct 1.C中struct struct里面只能放数据类型&#…...

代码随想录算法训练营 | 动态规划 part05

完全背包 有N件物品和一个最多能背重量为W的背包。第i件物品的重量是weight[i]&#xff0c;得到的价值是value[i] 。每件物品都有无限个&#xff08;也就是可以放入背包多次&#xff09;&#xff0c;求解将哪些物品装入背包里物品价值总和最大。 例子&#xff1a; 背包可容纳重…...

英特尔XPU大模型应用创新

...

仿Muduo库实现高并发服务器——socket网络通信模块

本项目就是基于TCP网络通信搭建的。 TCP: 客户端&#xff1a;socket(),connect(). 服务端&#xff1a;socket(),bind(),listen(),accept(). 下面代码就是对原生API网络套接字的封装。需要熟悉原生API网络套接字接口。 下面这段代码&#xff0c;没什么好讲的&#xff0c;就不…...

模型 神经网络(通俗解读)

系列文章 分享 模型&#xff0c;了解更多&#x1f449; 模型_思维模型目录。仿脑智能&#xff0c;深度学习&#xff0c;精准识别。 1 神经网络的应用 1.1 鸢尾花分类经典问题 神经网络的一个经典且详细的经典应用是鸢尾花分类问题 。主要是通过构建一个神经网络模型来自动区分…...

大数据学习栈记——Neo4j的安装与使用

本文介绍图数据库Neofj的安装与使用&#xff0c;操作系统&#xff1a;Ubuntu24.04&#xff0c;Neofj版本&#xff1a;2025.04.0。 Apt安装 Neofj可以进行官网安装&#xff1a;Neo4j Deployment Center - Graph Database & Analytics 我这里安装是添加软件源的方法 最新版…...

TDengine 快速体验(Docker 镜像方式)

简介 TDengine 可以通过安装包、Docker 镜像 及云服务快速体验 TDengine 的功能&#xff0c;本节首先介绍如何通过 Docker 快速体验 TDengine&#xff0c;然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。如果你不熟悉 Docker&#xff0c;请使用 安装包的方式快…...

如何在看板中有效管理突发紧急任务

在看板中有效管理突发紧急任务需要&#xff1a;设立专门的紧急任务通道、重新调整任务优先级、保持适度的WIP&#xff08;Work-in-Progress&#xff09;弹性、优化任务处理流程、提高团队应对突发情况的敏捷性。其中&#xff0c;设立专门的紧急任务通道尤为重要&#xff0c;这能…...

【C语言练习】080. 使用C语言实现简单的数据库操作

080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...

(转)什么是DockerCompose?它有什么作用?

一、什么是DockerCompose? DockerCompose可以基于Compose文件帮我们快速的部署分布式应用&#xff0c;而无需手动一个个创建和运行容器。 Compose文件是一个文本文件&#xff0c;通过指令定义集群中的每个容器如何运行。 DockerCompose就是把DockerFile转换成指令去运行。 …...

GruntJS-前端自动化任务运行器从入门到实战

Grunt 完全指南&#xff1a;从入门到实战 一、Grunt 是什么&#xff1f; Grunt是一个基于 Node.js 的前端自动化任务运行器&#xff0c;主要用于自动化执行项目开发中重复性高的任务&#xff0c;例如文件压缩、代码编译、语法检查、单元测试、文件合并等。通过配置简洁的任务…...

GitFlow 工作模式(详解)

今天再学项目的过程中遇到使用gitflow模式管理代码&#xff0c;因此进行学习并且发布关于gitflow的一些思考 Git与GitFlow模式 我们在写代码的时候通常会进行网上保存&#xff0c;无论是github还是gittee&#xff0c;都是一种基于git去保存代码的形式&#xff0c;这样保存代码…...

基于IDIG-GAN的小样本电机轴承故障诊断

目录 🔍 核心问题 一、IDIG-GAN模型原理 1. 整体架构 2. 核心创新点 (1) ​梯度归一化(Gradient Normalization)​​ (2) ​判别器梯度间隙正则化(Discriminator Gradient Gap Regularization)​​ (3) ​自注意力机制(Self-Attention)​​ 3. 完整损失函数 二…...

JavaScript 数据类型详解

JavaScript 数据类型详解 JavaScript 数据类型分为 原始类型&#xff08;Primitive&#xff09; 和 对象类型&#xff08;Object&#xff09; 两大类&#xff0c;共 8 种&#xff08;ES11&#xff09;&#xff1a; 一、原始类型&#xff08;7种&#xff09; 1. undefined 定…...

Python Einops库:深度学习中的张量操作革命

Einops&#xff08;爱因斯坦操作库&#xff09;就像给张量操作戴上了一副"语义眼镜"——让你用人类能理解的方式告诉计算机如何操作多维数组。这个基于爱因斯坦求和约定的库&#xff0c;用类似自然语言的表达式替代了晦涩的API调用&#xff0c;彻底改变了深度学习工程…...