登录
首页 >  Golang >  Go教程

Golang实现Prometheus计数器监控请求与错误

时间:2026-05-09 09:15:43 300浏览 收藏

本文深入讲解了在 Go 语言中如何正确使用 Prometheus Counter 指标记录 HTTP 请求与错误——强调必须通过 `prometheus.NewCounter` 构造并提前注册带 `ConstLabels` 的计数器,严禁使用全局变量或 `Set()` 方法;针对多维度监控(如按状态码分类错误),需改用线程安全的 `CounterVec` 并严格匹配标签顺序;同时揭示了常见陷阱:重复注册、`WithLabelValues` 参数错误导致 panic、高基数标签引发性能问题等,并演示了如何通过 `/metrics` 端点验证指标是否正常暴露,帮助开发者避开“看似能跑、实则失效”的监控盲区。

Golang怎么实现Prometheus Counter指标_Golang如何用计数器记录请求总数和错误总数【基础】

prometheus.NewCounter 定义请求总数和错误总数指标

Counter 是 Prometheus 最基础的指标类型,只增不减,适合记录请求数、错误数这类累积值。必须用 prometheus.NewCounter 构造,不能直接用整数变量代替——否则无法被 Prometheus server 抓取。

常见错误是直接在 handler 里用全局 int 变量自增,比如 reqCount++,这会导致指标不可暴露、无标签支持、无线程安全保证。

正确做法是提前注册带描述的 Counter:

var (
    httpRequestsTotal = prometheus.NewCounter(
        prometheus.CounterOpts{
            Name: "http_requests_total",
            Help: "Total number of HTTP requests.",
            // 注意:Labels 是预定义的维度,运行时不能动态增删
            ConstLabels: map[string]string{"app": "myserver"},
        },
    )
    httpErrorsTotal = prometheus.NewCounter(prometheus.CounterOpts{
        Name: "http_errors_total",
        Help: "Total number of HTTP errors.",
        ConstLabels: map[string]string{"app": "myserver"},
    })
)

然后在 init() 或服务启动时注册到默认注册器:

func init() {
    prometheus.MustRegister(httpRequestsTotal, httpErrorsTotal)
}

在 HTTP handler 中安全地调用 Inc()WithLabelValues()

Counter 的 Inc() 方法是线程安全的,可直接在并发 handler 中调用;但如果要按状态码、路径等打标签,必须用 prometheus.NewCounterVec,而不是单个 Counter。

例如想区分 200/404/500 错误,就不能复用 httpErrorsTotal.Inc(),而要定义 Vec:

httpErrorsByCode = prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "http_errors_by_code_total",
        Help: "HTTP errors grouped by status code.",
    },
    []string{"code"}, // 标签名
)
// 注册
prometheus.MustRegister(httpErrorsByCode)
<p>// 在 handler 中:
if err != nil {
httpErrorsByCode.WithLabelValues("500").Inc()
}</p>

注意:WithLabelValues() 的参数顺序必须严格匹配 NewCounterVec[]string 的顺序;传错类型或数量会 panic,不是静默失败。

另外,WithLabelValues() 返回的是一个 prometheus.Counter 实例,它本身也支持 Inc(),但不要重复注册——Vec 已注册,它的子指标不需要再注册。

为什么不能用 Set() 给 Counter 赋值

Counter 不支持 Set() 方法,调用会 panic 并报错:counter cannot be set。这是设计使然——Counter 表达的是“累计发生多少次”,不是“当前值是多少”。

如果你需要记录“当前活跃请求数”,该用 Gauge;如果硬要用 Counter 模拟重置(比如测试场景),唯一合法方式是重启进程(因为 Counter 一旦创建就不可归零)。

容易踩的坑:

  • 误把 httpRequestsTotal.Set(100) 当作初始化,结果 panic
  • 在单元测试中反复调用 MustRegister 同一指标,触发重复注册 panic(提示 duplicate metrics collector registration attempted
  • 在 goroutine 中未捕获 panic 导致整个 handler 崩溃(WithLabelValues 参数错误时会 panic)

暴露指标端点并验证是否生效

promhttp.Handler() 暴露 /metrics 端点即可,无需额外序列化逻辑:

http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", nil)

启动后访问 curl http://localhost:8080/metrics,应看到类似:

# HELP http_requests_total Total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{app="myserver"} 42
# HELP http_errors_by_code_total HTTP errors grouped by status code.
# TYPE http_errors_by_code_total counter
http_errors_by_code_total{app="myserver",code="500"} 3
http_errors_by_code_total{app="myserver",code="404"} 1

注意两点:

  • ConstLabels(如 app="myserver")会自动加到所有样本上;而 Vec 的动态标签(如 code)只出现在对应子指标行
  • 如果指标没出现,先检查是否漏掉 MustRegister;再确认 handler 是否真被调用(Counter 值为 0 不会显示在 /metrics 中,除非至少 Inc() 过一次)

标签维度不是越多越好——每个唯一标签组合都会生成独立时间序列,过度细分(比如把用户 ID 当标签)会导致 cardinality 爆炸,压垮 Prometheus server。

好了,本文到此结束,带大家了解了《Golang实现Prometheus计数器监控请求与错误》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>