You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go服务Prometheus响应无CPU指标,如何获取?

如何为Go服务获取CPU指标

问题根源

你当前代码的核心问题是自定义注册表未关联到指标暴露端点:
你创建了prometheus.NewRegistry()并注册了GoCollector和ProcessCollector,但promhttp.Handler()默认使用Prometheus的全局注册表,而非你自定义的reg。因此ProcessCollector提供的CPU指标没有被加载并暴露。

解决方案

使用promhttp.HandlerFor()替代默认的promhttp.Handler(),明确指定使用你的自定义注册表,这样就能加载所有注册到reg中的指标,包括CPU相关数据。

修改后的完整代码

package main

import (
	"fmt"
	"net/http"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/collectors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	var s []int
	idx := 0
	go func(){
		for {
			s = make([]int,idx%10)
			idx++
		}
	}()

	_ = s

	reg := prometheus.NewRegistry()

	reg.MustRegister(
		collectors.NewGoCollector(),
		collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
	)

	// 指定使用自定义注册表暴露指标
	http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("ERR:", err)
	}
}

可获取的CPU相关指标

重新启动服务后,请求/metrics会看到以下CPU相关指标:

  • process_cpu_seconds_total:进程自启动以来累计消耗的CPU秒数(counter类型),可通过计算两次采集的差值除以时间间隔得到CPU使用率。
  • process_cpu_percent:进程当前的CPU使用率百分比(gauge类型,部分版本的collector提供)。

内容的提问来源于stack exchange,提问作者Yura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 13:45:29