直接注册prometheus.newgocollector()即可暴露全部运行时指标,无需调用runtime.numgoroutine()等底层接口;必须显式挂载promhttp.handler()到/metrics路由,否则指标不暴露且抓取返回404或空响应。

直接注册 prometheus.NewGoCollector() 就能暴露全部运行时指标,不需要手动调用 runtime.NumGoroutine() 或 debug.ReadGCStats 等底层接口。
必须显式挂载 promhttp.Handler(),否则指标不暴露
只调用 prometheus.MustRegister(prometheus.NewGoCollector()) 不会自动创建 HTTP 路由。Prometheus 抓取时会返回 404 或空响应。
- 基础 HTTP 服务:用
http.Handle("/metrics", promhttp.Handler()),再http.ListenAndServe(":8080", nil) - Gin 框架:用
router.GET("/metrics", gin.WrapH(promhttp.Handler())) - Echo 框架:用
e.GET("/metrics", echo.WrapHandler(promhttp.Handler())) - 路径名必须和 Prometheus 配置里的
scrape_configs.job.metrics_path完全一致(默认是/metrics)
NewGoCollector() 自带完整标签,无需额外打点
注册后,/metrics 会直接输出 go_goroutines、go_memstats_alloc_bytes、go_gc_duration_seconds 等指标,且已带标准 label,例如 gc_phase="mark" 或 quantile="0.5"。
- 这些 label 是 Prometheus 官方定义的,Grafana 仪表盘(如 ID 4701 或 Go Runtime Dashboard)可直接识别
- 不要试图用
CounterVec重造go_goroutines——它不是业务计数器,而是瞬时快照,应由Gauge类型承载,而NewGoCollector已内部处理好 - 避免在 handler 中动态调用
runtime.NumGoroutine()并塞进NewGaugeFunc:这会让 metrics endpoint 变慢,且违背 Prometheus 的 pull 模型语义
别漏掉进程与构建指标,它们默认启用但容易被忽略
NewGoCollector() 实际注册三类指标:Go 运行时、进程(process_*)、构建信息(build_info),后两者常被误认为“无关”而关掉。
-
process_cpu_seconds_total和process_resident_memory_bytes对比go_memstats_*更贴近 OS 视角,适合排查内存泄漏或 CPU 争抢 -
build_info{goversion="go1.22.5",revision="abc123"}可用于多版本灰度监控,比如按revision分组看 GC 延迟差异 - 如需禁用某类,得用
prometheus.NewGoCollector(prometheus.WithGoCollectorMemStatsMetrics(), prometheus.WithGoCollectorRuntimeMetrics())显式控制,不能靠不注册来“省略”
真正容易踩坑的是指标生命周期管理:NewGoCollector() 必须在 HTTP server 启动前注册,且只能注册一次;若程序热重启或测试中多次 init,会 panic。这不是运行时问题,而是注册表冲突——错误信息是 duplicate metrics collector registration attempted,得靠包级变量 + 单次 init 保证。
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!











