Go-Prometheus指标采集与监控全栈实践

Go-Prometheus指标采集与监控从Counter到Histogram全栈实践

文章导语

Prometheus是CNCF毕业的监控标准,Go的prometheus/client_golang库是集成Prometheus的首选。本文基于Gin构建完整的指标监控体系。

一、指标类型

go 复制代码
var (
    httpRequestsTotal = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Total number of HTTP requests",
        },
        []string{"method", "path", "status"},
    )
    
    httpRequestDuration = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Name:    "http_request_duration_seconds",
            Help:    "HTTP request latency",
            Buckets: prometheus.DefBuckets,
        },
        []string{"method", "path"},
    )
)

func init() {
    prometheus.MustRegister(httpRequestsTotal)
    prometheus.MustRegister(httpRequestDuration)
}

二、Gin监控中间件

go 复制代码
func PrometheusMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        start := time.Now()
        c.Next()
        
        status := strconv.Itoa(c.Writer.Status())
        httpRequestsTotal.WithLabelValues(c.Request.Method, c.FullPath(), status).Inc()
        httpRequestDuration.WithLabelValues(c.Request.Method, c.FullPath()).
            Observe(time.Since(start).Seconds())
    }
}

// 暴露/metrics端点
r.GET("/metrics", gin.WrapH(promhttp.Handler()))

三、自定义业务指标

go 复制代码
var (
    ordersProcessed = prometheus.NewCounter(prometheus.CounterOpts{
        Name: "orders_processed_total",
        Help: "Processed orders count",
    })
    
    activeUsers = prometheus.NewGauge(prometheus.GaugeOpts{
        Name: "active_users",
        Help: "Currently active users",
    })
)

四、全文总结

  1. Counter累计计数,只增不减
  2. Gauge瞬时值,可增可减
  3. Histogram分布统计,自动计算分位数
  4. Summary客户端分位数计算

参考文献

  1. Prometheus Go Client: https://github.com/prometheus/client_golang
  2. Prometheus文档
  3. Google SRE Book - Monitoring
相关推荐
码士集团小青14 小时前
从对标 Java 到对标 Go:Native AOT 的“无痛化“之路,走到哪一站了?
golang
右耳朵猫AI15 小时前
Go周刊2026W36 | Go 1.27.1 发布、TinyGo 0.42、HTTP/2 原生迁入 net/http、quic-go 0.62
redis·http·golang
大树911 天前
把 Java 项目从手动 SCP 升级到 Gitee Go 自动部署:一份踩坑实录
java·golang·gitee
lmy_loveF1 天前
go 切换go version 版本
开发语言·后端·golang
智购科技自动贩卖机1 天前
自动售货机嵌入式系统安全加固实践:从Go语言国密算法到硬件防拆的工程化落地
大数据·人工智能·后端·安全·golang·系统安全
妙码生花2 天前
使用git更新ai-go-admin框架
前端·人工智能·git·golang·typescript·php
王的宝库2 天前
GO常用标准库包
开发语言·后端·golang
平头哥AI2 天前
Day 13 | 一个函数回两个值:Go 的 error 是从哪冒出来的
开发语言·后端·golang
我不会起名字3222 天前
一天一道算法题(29):单调栈
java·数据结构·python·算法·leetcode·golang·单调栈