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
相关推荐
圣殿骑士-Khtangc10 小时前
Go-TLS-SSL安全通信从证书管理到双向认证
golang
圣殿骑士-Khtangc11 小时前
Go可观测性三支柱Logs-Metrics-Traces集成实战
golang
名字还没想好☜11 小时前
Go 的 database/sql 连接池实战:SetMaxOpenConns 怎么配、连接泄漏怎么查
数据库·sql·golang·go·数据库连接池
圣殿骑士-Khtangc11 小时前
Go-Docker多阶段构建与容器化最佳实践
golang
灯澜忆梦16 小时前
【基于GO的Web开发3】gin框架_HTML渲染
前端·golang·gin
码农大叔的博客1 天前
golang示例:switch
开发语言·后端·golang
圣殿骑士-Khtangc2 天前
Go面试核心考点之GMP调度器源码级深度解析
golang
xcLeigh2 天前
Go入门:无类型常量与类型常量的区别
服务器·开发语言·golang
泡沫冰@2 天前
GO 语言基础
开发语言·算法·golang