用 Prometheus 监控 Go 应用:埋点实战
Go 应用接入 Prometheus 的完整教程:prometheus/client_golang 暴露 /metrics、Counter/Gauge/Histogram 三种指标埋点、中间件统一采集 HTTP 指标、常见问题。
Go 应用接入 Prometheus 只需一个库:prometheus/client_golang。暴露 /metrics 端点,埋点自定义指标,Prometheus 来抓取——本文走完整个流程。
第一步:暴露默认指标
以下示例使用 Go 1.23 或更新版本。先在一个空目录初始化 Go 模块,再安装示例所用版本的客户端库:
go mod init example.com/go-metrics
go get github.com/prometheus/client_golang/prometheus/promhttp@v1.23.2
把下面代码保存为 main.go,运行 go run .。默认注册表已注册 Go 运行时和进程采集器,promhttp.Handler() 将其暴露在 HTTP 端点:
package main
import (
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe("127.0.0.1:8080", mux))
}
访问 http://127.0.0.1:8080/metrics 可查看 go_goroutines、go_memstats_* 等默认指标;process_* 的可用指标取决于操作系统。使用自建 Registry 时,要显式注册所需采集器,并用 promhttp.HandlerFor 暴露该 Registry。
第二步:埋点业务指标
Counter:累计请求数
http_requests_total 按路由模板、HTTP 方法和状态码统计已返回的业务请求。请求处理器正常返回但未显式写状态码时,按 200 计数。
Gauge:当前活跃请求
http_active_requests 在进入被包装的处理器时加一,离开时减一。它反映当前进入处理器的请求数。
Histogram:请求延迟分布
http_request_duration_seconds 记录处理器执行耗时,单位为秒,按路由模板分组。桶边界应覆盖关心的时延,例如 300 毫秒对应 0.3 秒的桶。
第三步:统一中间件
用下面的完整版本替换上一步的 main.go。用 promhttp 包装已注册的业务处理器,同时将 /metrics 留在埋点之外:
package main
import (
"fmt"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
const route = "/orders/{id}"
requests := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Completed calls to the instrumented handler.",
}, []string{"route", "method", "code"})
active := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "http_active_requests",
Help: "Calls currently executing in the instrumented handler.",
})
duration := prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Time spent in the instrumented handler in seconds.",
Buckets: []float64{0.01, 0.05, 0.1, 0.3, 0.5, 1, 2.5, 5},
}, []string{"route"})
prometheus.MustRegister(requests, active, duration)
orders := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "missing" {
http.NotFound(w, r)
return
}
fmt.Fprintln(w, "order", id)
})
labels := prometheus.Labels{"route": route}
instrumented := promhttp.InstrumentHandlerInFlight(active,
promhttp.InstrumentHandlerCounter(requests.MustCurryWith(labels),
promhttp.InstrumentHandlerDuration(duration.MustCurryWith(labels), orders),
),
)
mux := http.NewServeMux()
mux.Handle("GET "+route, instrumented)
mux.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe("127.0.0.1:8080", mux))
}
⚠️ 最关键的坑:标签用路由模板(/orders/{id}),不能用原始路径(/orders/123)。原始路径可能让每个 ID 都生成一组新时间序列。模板由注册路由时传入;Gin 的 c.FullPath()、Echo 的 c.Path() 与 chi 的 RouteContext 也能提供各自框架的路由模板,需按框架的路由匹配时机读取。
例如访问 /orders/123 和 /orders/missing,再抓取 /metrics。两次请求的 route 相同,code 分别为 200 和 404。路由器生成的未匹配 404 或方法不允许的 405 不经过该包装;若处理器向外抛出 panic,Counter 和 Histogram 不记录这次调用,Gauge 仍会减一。耗时只覆盖服务端处理器,不能代表客户端收到响应的耗时。promhttp 中间件
第四步:Prometheus 抓取
示例只监听回环地址,下面的配置用于与 Go 应用运行在同一台主机、同一网络命名空间的 Prometheus。远程抓取时,使用采集器可达的地址,并限制对指标端点的访问。
scrape_configs:
- job_name: go-app
scrape_interval: 15s
static_configs:
- targets: ['127.0.0.1:8080']
在有多次成功抓取后,分别查询按路由与状态码分组的每秒请求数,以及按路由估算的 P99(秒):
sum by (route, code) (rate(http_requests_total{job="go-app"}[5m]))
histogram_quantile(
0.99,
sum by (le, route) (rate(http_request_duration_seconds_bucket{job="go-app"}[5m]))
)
经典直方图要先对各桶计数器求速率,再聚合并保留 le 标签。跨实例汇总时,使用相同的桶边界。Prometheus 查询函数
同一个 /metrics 端点也可交给观测云 DataKit 的 prom 采集器抓取:在 urls 中配置端点地址,继续复用这里定义的 Counter、Gauge 和 Histogram [1]。采集后检查指标名称、标签和单位,再建立对应查询;采集格式相同不代表原有 PromQL 可以原样使用。
常见问题(FAQ)
Q:Counter 的值重启后归零,会不会丢数据?
A:Prometheus 的 rate() 和 increase() 会调整样本中检测到的重置。两次抓取之间发生、且未被采到的增量无法恢复,因此不能用它们代替精确对账。
Q:goroutine 数突然飙升说明什么?
A:可能是并发请求增多,也可能是 goroutine 阻塞或未退出。若流量恢复后数量仍持续升高,可用 pprof 的 goroutine profile 查看堆栈和等待位置。
Q:默认指标里 process_ 和 go_ 有什么区别?**
A:go_* 是 Go 运行时视角(GC、goroutine、堆),process_* 是操作系统进程视角(CPU 时间、RSS、文件描述符)。排查内存问题两个都要看。
[1]: 观测云文档《Prometheus 采集》https://docs.guance.com/integrations/prom/