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
相关推荐
茉莉玫瑰花茶4 小时前
GO [ 函数 ]
开发语言·后端·golang
茉莉玫瑰花茶5 小时前
GO [ 类型 ]
开发语言·数据库·golang
茉莉玫瑰花茶6 小时前
GO [ 并发 ]
开发语言·后端·golang
蓝宝石的傻话6 小时前
onvif-go(mickeyzzc/onvif-go v2)完整参考手册:从建工程到写出自己的 NVR 接入
开发语言·后端·golang
茉莉玫瑰花茶9 小时前
GO [ 接口 ]
服务器·数据库·golang
茉莉玫瑰花茶10 小时前
GO [ 文件 ]
服务器·golang
念何架构之路1 天前
go-grpc使用
rpc·golang
小小龙学IT1 天前
Go 泛型(Generics)深度解析:从类型参数到生产实践
开发语言·数据库·golang
不会写DN1 天前
Go日志库工程选型与逃逸分析评测报告
java·服务器·golang