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
相关推荐
http阿拉丁神猫3 小时前
Go语言入门笔记:从基础到开发环境搭建(二)
开发语言·笔记·golang
紧跟先前的步伐11 小时前
Go AI Agent 实战 03|Token、上下文窗口与模型调用成本
java·人工智能·golang
紧跟先前的步伐14 小时前
Go AI Agent 实战 02|大语言模型(LLM)到底是怎么工作的
人工智能·语言模型·golang
golang学习记19 小时前
Python vs Go:2026年到底该怎么选
java·vscode·python·golang·pycharm·goland
茉莉玫瑰花茶20 小时前
GO [ 内存与变量逃逸分析 ]
开发语言·后端·golang
9624562 天前
Go EVM 链上数据平台实践:从 RPC Demo 到可演进架构
rpc·架构·golang
银河技术2 天前
从脚本到 Operator:用 Go 构建可靠的微服务自动扩缩容控制器
开发语言·微服务·golang
云和数据.ChenGuang3 天前
Golang AI 工程师路线图:从入门到实战
开发语言·人工智能·后端·golang
报错小能手3 天前
内存管理 垃圾回收面试题
golang
tachibana24 天前
Go 语言里的 Context 是什么?
开发语言·后端·golang·go·语言