golang+prometheus+Grafana可视化性能监控

最近需要监控Golang API的性能,学了Golang的Prometheus,做了相关笔记,分享一下,哪里理解的不对欢迎大家帮忙指正吖~

参考链接:

Prometheus 监控服务 Golang 应用接入-接入指南-文档中心-腾讯云

1. Golang Prometheus

注意:golang 1.15以上才支持prometheus,安装需要用到的包:

1.1  公开性能数据的接口

相关代码已经上传到对应gitcode,可进行搜索下载:golang-prometheus-testGitCode - 全球开发者的开源社区,开源代码托管平台

我这里的golang版本是1.16的对应安装prometheus应该是1.13.0版本, 具体的go.mod文件:

定义一个能查看性能的接口:

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
	"runtime"
	"sync"
	"time"
)

type Collector struct {
	// HTTP请求相关指标
	requestCounter  *prometheus.CounterVec
	requestDuration *prometheus.HistogramVec
	requestInFlight *prometheus.GaugeVec

	// 系统资源指标
	cpuUsage       *prometheus.GaugeVec
	memoryUsage    *prometheus.GaugeVec
	goroutineCount prometheus.Gauge

	// 业务指标
	businessCounter *prometheus.CounterVec
	queueLength     *prometheus.GaugeVec

	// 错误指标
	errorCounter *prometheus.CounterVec

	mu sync.RWMutex
}

func NewCollector(namespace string) *Collector {
	return &Collector{
		requestCounter: promauto.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: namespace,
				Name:      "http_requests_total",
				Help:      "Total number of HTTP requests",
			},
			[]string{"method", "path", "status"},
		),

		requestDuration: promauto.NewHistogramVec(
			prometheus.HistogramOpts{
				Namespace: namespace,
				Name:      "http_request_duration_seconds",
				Help:      "HTTP request duration in seconds",
				Buckets:   []float64{0.1, 0.3, 0.5, 0.7, 0.9, 1.0, 1.5, 2.0},
			},
			[]string{"method", "path"},
		),

		requestInFlight: promauto.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: namespace,
				Name:      "http_requests_in_flight",
				Help:      "Current number of HTTP requests being processed",
			},
			[]string{"method"},
		),
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值