prometheus监控应用数据(一)

news2024/9/29 13:32:57

prometheus监控应用数据(一)

以下代码实现均使用go语言,至于其他语言请参照其他语言的prometheus api文档

  1. 获取go package: prometheus: go get -u github.com/prometheus/client_golang/prometheus
  2. 搭建程序基本骨架
    • IP地址暂定为: localhost
    • 启用prometheus的监控端口是2112
    • /metrics路由进行访问,所以获取监控数据的完整访问路径为: localhost:2122/metrics
    package test
    
    import (
        "github.com/prometheus/client_golang/prometheus/promhttp"
        "net/http"
        "testing"
    )
    
    func TestPrometheus(t *testing.T) {
        http.Handle("/metrics", promhttp.Handler())
        http.ListenAndServe(":2112", nil)
    }
    
    执行结果如下:
    # HELP go_gc_duration_seconds A summary of the pause duration of garbage collection cycles.
    # TYPE go_gc_duration_seconds summary
    go_gc_duration_seconds{quantile="0"} 0
    go_gc_duration_seconds{quantile="0.25"} 0
    go_gc_duration_seconds{quantile="0.5"} 0
    go_gc_duration_seconds{quantile="0.75"} 0
    go_gc_duration_seconds{quantile="1"} 0
    go_gc_duration_seconds_sum 0
    go_gc_duration_seconds_count 0
    # HELP go_goroutines Number of goroutines that currently exist.
    # TYPE go_goroutines gauge
    go_goroutines 8
    # HELP go_info Information about the Go environment.
    # TYPE go_info gauge
    go_info{version="go1.19.2"} 1
    # HELP go_memstats_alloc_bytes Number of bytes allocated and still in use.
    # TYPE go_memstats_alloc_bytes gauge
    go_memstats_alloc_bytes 1.622128e+06
    # HELP go_memstats_alloc_bytes_total Total number of bytes allocated, even if freed.
    # TYPE go_memstats_alloc_bytes_total counter
    go_memstats_alloc_bytes_total 1.622128e+06
    # HELP go_memstats_buck_hash_sys_bytes Number of bytes used by the profiling bucket hash table.
    # TYPE go_memstats_buck_hash_sys_bytes gauge
    go_memstats_buck_hash_sys_bytes 1.449315e+06
    # HELP go_memstats_frees_total Total number of frees.
    # TYPE go_memstats_frees_total counter
    go_memstats_frees_total 1955
    # HELP go_memstats_gc_sys_bytes Number of bytes used for garbage collection system metadata.
    # TYPE go_memstats_gc_sys_bytes gauge
    go_memstats_gc_sys_bytes 5.975528e+06
    # HELP go_memstats_heap_alloc_bytes Number of heap bytes allocated and still in use.
    # TYPE go_memstats_heap_alloc_bytes gauge
    go_memstats_heap_alloc_bytes 1.622128e+06
    # HELP go_memstats_heap_idle_bytes Number of heap bytes waiting to be used.
    # TYPE go_memstats_heap_idle_bytes gauge
    go_memstats_heap_idle_bytes 4.530176e+06
    # HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use.
    # TYPE go_memstats_heap_inuse_bytes gauge
    go_memstats_heap_inuse_bytes 3.629056e+06
    # HELP go_memstats_heap_objects Number of allocated objects.
    # TYPE go_memstats_heap_objects gauge
    go_memstats_heap_objects 4503
    # HELP go_memstats_heap_released_bytes Number of heap bytes released to OS.
    # TYPE go_memstats_heap_released_bytes gauge
    go_memstats_heap_released_bytes 4.530176e+06
    # HELP go_memstats_heap_sys_bytes Number of heap bytes obtained from system.
    # TYPE go_memstats_heap_sys_bytes gauge
    go_memstats_heap_sys_bytes 8.159232e+06
    # HELP go_memstats_last_gc_time_seconds Number of seconds since 1970 of last garbage collection.
    # TYPE go_memstats_last_gc_time_seconds gauge
    go_memstats_last_gc_time_seconds 0
    # HELP go_memstats_lookups_total Total number of pointer lookups.
    # TYPE go_memstats_lookups_total counter
    go_memstats_lookups_total 0
    # HELP go_memstats_mallocs_total Total number of mallocs.
    # TYPE go_memstats_mallocs_total counter
    go_memstats_mallocs_total 6458
    # HELP go_memstats_mcache_inuse_bytes Number of bytes in use by mcache structures.
    # TYPE go_memstats_mcache_inuse_bytes gauge
    go_memstats_mcache_inuse_bytes 4672
    # HELP go_memstats_mcache_sys_bytes Number of bytes used for mcache structures obtained from system.
    # TYPE go_memstats_mcache_sys_bytes gauge
    go_memstats_mcache_sys_bytes 16352
    # HELP go_memstats_mspan_inuse_bytes Number of bytes in use by mspan structures.
    # TYPE go_memstats_mspan_inuse_bytes gauge
    go_memstats_mspan_inuse_bytes 46648
    # HELP go_memstats_mspan_sys_bytes Number of bytes used for mspan structures obtained from system.
    # TYPE go_memstats_mspan_sys_bytes gauge
    go_memstats_mspan_sys_bytes 48960
    # HELP go_memstats_next_gc_bytes Number of heap bytes when next garbage collection will take place.
    # TYPE go_memstats_next_gc_bytes gauge
    go_memstats_next_gc_bytes 4.194304e+06
    # HELP go_memstats_other_sys_bytes Number of bytes used for other system allocations.
    # TYPE go_memstats_other_sys_bytes gauge
    go_memstats_other_sys_bytes 1.081389e+06
    # HELP go_memstats_stack_inuse_bytes Number of bytes in use by the stack allocator.
    # TYPE go_memstats_stack_inuse_bytes gauge
    go_memstats_stack_inuse_bytes 229376
    # HELP go_memstats_stack_sys_bytes Number of bytes obtained from system for stack allocator.
    # TYPE go_memstats_stack_sys_bytes gauge
    go_memstats_stack_sys_bytes 229376
    # HELP go_memstats_sys_bytes Number of bytes obtained from system.
    # TYPE go_memstats_sys_bytes gauge
    go_memstats_sys_bytes 1.6960152e+07
    # HELP go_threads Number of OS threads created.
    # TYPE go_threads gauge
    go_threads 6
    # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds.
    # TYPE process_cpu_seconds_total counter
    process_cpu_seconds_total 0.046875
    # HELP process_max_fds Maximum number of open file descriptors.
    # TYPE process_max_fds gauge
    process_max_fds 1.6777216e+07
    # HELP process_open_fds Number of open file descriptors.
    # TYPE process_open_fds gauge
    process_open_fds 105
    # HELP process_resident_memory_bytes Resident memory size in bytes.
    # TYPE process_resident_memory_bytes gauge
    process_resident_memory_bytes 1.3832192e+07
    # HELP process_start_time_seconds Start time of the process since unix epoch in seconds.
    # TYPE process_start_time_seconds gauge
    process_start_time_seconds 1.686533234e+09
    # HELP process_virtual_memory_bytes Virtual memory size in bytes.
    # TYPE process_virtual_memory_bytes gauge
    process_virtual_memory_bytes 2.3031808e+07
    # HELP promhttp_metric_handler_requests_in_flight Current number of scrapes being served.
    # TYPE promhttp_metric_handler_requests_in_flight gauge
    promhttp_metric_handler_requests_in_flight 1
    # HELP promhttp_metric_handler_requests_total Total number of scrapes by HTTP status code.
    # TYPE promhttp_metric_handler_requests_total counter
    promhttp_metric_handler_requests_total{code="200"} 0
    promhttp_metric_handler_requests_total{code="500"} 0
    promhttp_metric_handler_requests_total{code="503"} 0
    
  3. 监控程序自定义数据
    以下定义要进行监控的业务数据
    • 当前进入课堂的学生数量
    • 当前进入课堂的学生的详细信息:ID和Name
    var (
        // 当前在课堂中的学生数量
        studentNumber = promauto.NewCounter(prometheus.CounterOpts{
            Name: "StudentNumber",
            Help: "The number of students who has entered into the class room",
        })
    
        // 当前在课堂中的学生详情:ID+Name
        studentDetails = prometheus.NewGaugeVec(prometheus.GaugeOpts{
            Name: "EveryStudentDetail",
            Help: "Every student detail",
        }, []string{"id", "name"})
    )
    
  4. 注册业务数据到prometheus框架
prometheus.MustRegister(studentDetails)
  1. 实现以下业务逻辑

    • 每隔5秒一个学生进入课堂,并将学生数统计到studentNumber
            id := 0
            name := "student-"
            for {
                room.AddStudent(strconv.Itoa(id), name+strconv.Itoa(id))
                studentNumber.Inc()
                time.Sleep(time.Second * 5)
                id++
            }
    
    • 每隔2s将课堂中的学生统计到我们第3步中定义的监控变量studentDetails
            ticker := time.NewTicker(time.Second * 2)
            for {
                select {
                case <-ticker.C:
                    RefreshStuDetails()
                }
            }
            
    func RefreshStuDetails() {
        gClassRoom.mu.Lock()
        defer gClassRoom.mu.Unlock()
    
        studentDetails.Reset()
        for _, student := range gClassRoom.students {
            studentDetails.WithLabelValues(student.ID, student.Name)
        }
    }
    
  2. 运行函数TestPrometheus,程序完整代码详见第8步

  3. 打开浏览器,访问地址localhost:2122/metrics,即可看到形如第2步中的输出内容,与之不同的是,内容中新增了StudentNumberEveryStudentDetail相关内容的条项,条项下分别输出了当前课堂的学生数量,当前课堂学生的详细信息。如下图所示:
    在这里插入图片描述

  4. 程序完整代码如下:

package test

import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"log"
	"net/http"
	"strconv"
	"sync"
	"testing"
	"time"
)

type Student struct {
	ID   string
	Name string
}

// 以下定义课堂和学生相关的数据结构,出于封装考虑,可以放到另外一个文件中, 这里为了演示
// 先放到一个文件中
type ClassRoom struct {
	mu       sync.RWMutex
	students map[string]*Student
}

func NewClassRoom() *ClassRoom {
	return &ClassRoom{
		students: make(map[string]*Student),
	}
}

func (r *ClassRoom) AddStudent(id string, name string) {
	r.mu.Lock()
	defer r.mu.Unlock()

	r.students[id] = &Student{
		ID:   id,
		Name: name,
	}
}

// 课堂、学生相关数据结构定义结束

var gClassRoom *ClassRoom

// 定义需要监控的数据结构
var (
	// 当前在课堂中的学生数量
	studentNumber = promauto.NewCounter(prometheus.CounterOpts{
		Name: "StudentNumber",
		Help: "The number of students who has entered into the class room",
	})

	// 当前在课堂中的学生详情:ID+Name
	studentDetails = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Name: "EveryStudentDetail",
		Help: "Every student detail",
	}, []string{"id", "name"})
)

// StudentEnterClassRoom Simulate the scene where students enter the classroom every 5 seconds
func StudentEnterClassRoom(r *ClassRoom) {
	go func(room *ClassRoom) {
		defer func() {
			if p := recover(); p != nil {
				log.Panicf("%v", p)
			}
		}()

		id := 0
		name := "student-"
		for {
			room.AddStudent(strconv.Itoa(id), name+strconv.Itoa(id))
			studentNumber.Inc()
			time.Sleep(time.Second * 5)
			id++
		}

	}(r)
}

func TestPrometheus(t *testing.T) {
	gClassRoom = NewClassRoom()
	StudentEnterClassRoom(gClassRoom) // 每过5s一个学生进入课堂

	// 将需要的监控数据注册到prometheus
	prometheus.MustRegister(studentDetails)

	// 每2s刷新一下监控数据
	go func() {
		defer func() {
			if p := recover(); p != nil {
				log.Panicf("%v", p)
			}
		}()

		ticker := time.NewTicker(time.Second * 2)
		for {
			select {
			case <-ticker.C:
				RefreshStuDetails()
			}
		}
	}()

	http.Handle("/metrics", promhttp.Handler())
	http.ListenAndServe(":2112", nil)
}

func RefreshStuDetails() {
	gClassRoom.mu.Lock()
	defer gClassRoom.mu.Unlock()

	studentDetails.Reset()
	for _, student := range gClassRoom.students {
		studentDetails.WithLabelValues(student.ID, student.Name)
	}
}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

互联网大厂Java面试题1500+附答案详解(2023版)

很多 Java 工程师的技术不错&#xff0c;但是一面试就头疼&#xff0c;10 次面试 9 次都是被刷&#xff0c;过的那次还是去了家不知名的小公司。 问题就在于&#xff1a;面试有技巧&#xff0c;而你不会把自己的能力表达给面试官。 应届生&#xff1a;你该如何准备简历&#…

2020310

Selenium: 基于WebDriver协议的 Web应用程序测试的工具 精简版&#xff1a; selenium脚本通过http请求发送命令和参数给httpserver httpserver通过json wire protocol格式转发命令和参数给webdriver webdriver通过原生API或者JavaScript代码执行操作给浏览器 浏览器通过json wi…

材料微观结构表征技术:电子背散射衍射EBSD

材料微观结构表征技术&#xff1a;电子背散射衍射EBSD 电子背散射衍射&#xff08;EBSD&#xff09;是一种材料表征技术&#xff0c;通过使用电子束对材料进行照射&#xff0c;并测量背向散射的电子的衍射模式&#xff0c;可以提供关于材料微观结构的详细信息。这项技术结合了…

DAY 75 【分布式应用】消息队列之卡夫卡 + EFLFK集群部署

pache公司的软件包官方下载地址&#xff1a;archive.apache.org/dist/ 注&#xff1a;kafka从3.0版本之后&#xff0c;不再依赖zookeeper Zookeeper 概述 官方下载地址&#xff1a;https://archive.apache.org/dist/zookeeper/ Zookeeper 定义 Zookeeper是一个开源的分布式…

【Linux脚本篇】循环语句-for

目录 &#x1f341;for的语法格式 &#x1f341;for循环案例 &#x1f343;案例一&#xff1a;循环创建文件 &#x1f343;案例二&#xff1a;应用引号或转义符 &#x1f343;案例三&#xff1a;从变量中取值 &#x1f343;案例四&#xff1a;从命令中取值 &#x1f343;案例五…

Vulkan入门精要

Vulkan入门精要 (fuxiii.github.io)https://fuxiii.github.io/Essentials.of.Vulkan/

开始在适用于 Linux 的 Windows 子系统上使用 Git

目录 Git 可以安装在 Windows 和 WSL 上安装 GitGit 配置文件设置Git 凭据管理器设置使用 SSH 的 GitAzure 的其他配置添加 Git Ignore 文件Git 和 VS CodeGit 行尾其他资源 Git 是最常用的版本控制系统。 使用 Git&#xff0c;可以跟踪对文件所做的更改&#xff0c;以便记录已…

java使用aspose.pdf或者spire.pdf 将pdf文件转word,实测

1. aspose.pdf aspose.pdf不是破解版的只能转3页&#xff0c;所以我弄了个破解版&#xff0c; aspose.pdf破解版在网上都有破解方法也比较简单&#xff0c;这里就不说了&#xff0c;直接引入破解版的jar包&#xff0c;在这里我用的是aspose-pdf-21.11.jar版本&#xff0c;代码…

【电路】电路与电子技术基础 课堂笔记 第9章 集成运算放大器基础

本章的研究对象是集成运算放大器的应用&#xff0c; 主要关注如何利用理想运放的特点&#xff0c;分析放大电路&#xff0c; 不讨论继承运放的工作原理和内部结构。 9.3 集成运放的主要参数与选择 9.4 集成运放的应用 集成运放应用于信号运算&#xff0c;信号处理&#xff…

调用阿里API实现手机号归属地查询

调用阿里API实现手机号归属地查询 1&#xff0e;作者介绍2&#xff0e;号码归属地介绍2.1 什么是手机号码归属地&#xff1f;2.2 为什么需要手机号码归属地&#xff1f;2.3 手机号码归属地查询对个人的运用 3&#xff0e;调用阿里API实现手机号归属地查询3.1阿里API调用3.2补充…

BYC30W-600P-ASEMI代理NXP快恢复二极管BYC30W-600P

编辑&#xff1a;ll BYC30W-600P-ASEMI代理NXP快恢复二极管BYC30W-600P 型号&#xff1a;BYC30W-600P 品牌&#xff1a;NXP/恩智浦 封装&#xff1a;TO-247-2L 最大漏源电流&#xff1a;30A 漏源击穿电压&#xff1a;600V 引脚数量&#xff1a;2 恢复时间&#xff1a;2…

JavaScript:获取当前日期、星期、时间 | Data对象

文章目录 1 Date对象2 代码示例3 获取 yyyy-MM-dd 格式的日期 1 Date对象 JavaScript 中的 Date 对象表示日期和时间。Date 对象基于自 1970 年 1 月 1 日 00:00:00 UTC&#xff08;协调世界时&#xff09;以来的毫秒数。以下是 Date 对象的一些常用方法和属性。 getFullYear…

H5页面这样测,业务方反馈 0 Bug!

部门最近的H5相关项目挺多的&#xff0c;由于团队之前接触的大多是Web项目&#xff0c;很少涉及H5&#xff0c;想着给团队成员培训下&#xff0c;减少漏测率&#xff0c;于是整理了一个文档。 别说&#xff0c;效果还挺不错的&#xff0c;连着上线6个版本&#xff0c;都没有收…

Python3数据分析与挖掘建模(10)多因子:复合分析-交叉分析与实现示例

1. 复合分析 1.1 概述 复合分析&#xff08;Factorial Analysis&#xff09;是一种统计分析方法&#xff0c;用于研究多个因素对观测结果的影响&#xff0c;并探究各个因素之间的相互作用效应。 在复合分析中&#xff0c;研究者会选择多个因素&#xff08;也称为处理变量或独…

路由器WiFi密码怎么设置?这样做可以快速设置!

案例&#xff1a;我在外面租房&#xff0c;买了一个路由器&#xff0c;为了不让别人使用&#xff0c;我想设置一个密码。但我不知道如何操作。路由器怎么设置密码&#xff1f;求方法分享&#xff01; 如今&#xff0c;Wi-Fi已成为日常生活中不可或缺的一部分。为了保障个人和家…

4. LockSupport与线程中断

4.1 线程中断机制 4.1.1 从阿里蚂蚁金服面试题讲起 Java.lang.Thread下的三个方法: ● 如何中断一个运行中的线程&#xff1f; ● 如何停止一个运行中的线程&#xff1f; 4.1.2 什么是中断机制 ● 首先&#xff0c;一个线程不应该由其他线程来强制中断或停止&#xff0c;而是应…

排水管网监测,万宾排水管网在线监测系统

城市排水管网是保障城市环境卫生的重要基础设施。然而&#xff0c;传统的排水管网管理方式存在许多问题.通过排水管网在线监测系统的建设&#xff0c;可以实现对管网上窨井井盖状态、管网液位、管网流量、管网水质等数据采集&#xff0c;实时掌握排水管网运行状况&#xff0c;为…

@足智多谋的你,联网智能门锁试卷(2023高考版)正式发布!

千淘万漉虽辛苦&#xff0c;吹尽狂沙始到金。2023年的高考已于上周正式结束。湖南省高考成绩和录取控制分数线将在6月25日正式公布。广大学子历经一千多个日夜的努力&#xff0c;即将在这一天见证结果。 其实&#xff0c;当我们真正走出校园才发现&#xff0c;学无止境&#x…

敏捷项目管理

在了解敏捷项目管理之前&#xff0c;我们先看下敏捷和传统项目管理有什么区别。 传统项目管理&#xff1a;阶段式项目管理模式。 制定详细的计划和步骤&#xff0c;按计划执行&#xff0c;直到所有的计划执行全部结束。 敏捷项目管理模式&#xff0c;从愿景和高价值的目标出发…

V5.0.X版本 EMQX安装、卸载 以及使用

V5.0.X版本 EMQX安装、卸载 以及使用 一、卸载二、下载安装2.1 下载2.2 安装2.2.1 rpm安装2.2.2 tar安装 2.3 测试启动 三、EMQX使用 回到目录    回到末尾 EMQX为大规模分布式物联网 MQTT 消息服务器。提供高效可靠连接海量物联网设备&#xff0c;实时处理分发消息与事件流数…