应使用 prometheus.NewCounter 定义请求总数和错误总数指标,提前注册带 ConstLabels 的 Counter 并在 handler 中调用 Inc(),不可用全局变量或 Set();需按维度打标签时改用 NewCounterVec。

用 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 已注册,它的子指标不需要再注册。
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
为什么不能用 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免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










