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
相关推荐
利威尔xu11 小时前
Go map 底层崩溃:3 个 goroutine 并发写同一张 map,fatal error 崩掉整个服务
golang·源码·map·并发·后端开发
利威尔xu2 天前
2026-11-08-Go-defer-panic-recover面试
面试·golang
JWASX2 天前
【Go】map 源码解析 - group
后端·golang·map·源码分析
联犀3 天前
纯 Go 的 CAD 开源库 go-cad:直接解析 DWG/DXF,现在也能导出 PDF
开发语言·golang·pdf
FungLeo3 天前
成为全栈·Go 后端篇·三轮代码审阅之后:把可读性和证据做成工程规则
golang·go·ast·静态检查·成为全栈·代码审阅
联犀3 天前
联犀 Go SIMD 实战:视频转码从 16.5ms 到 5.46ms
开发语言·golang·音视频
紧跟先前的步伐4 天前
Go AI Agent 实战 28|Agent 的预算、超时与停止条件
开发语言·人工智能·后端·ai·golang
利威尔xu4 天前
2026-11-05-Go内存管理面试
面试·golang
Zenova EdgeOS6 天前
Go 工业边缘错误处理实战:用 errors 构建可追溯错误链
开发语言·数据库·golang
JavaPub-rodert6 天前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang