如何在Golang中仅展示自定义Prometheus指标而非默认指标
解决Prometheus /metrics仅展示自定义指标的问题
要只返回你定义的requests指标,核心是不使用Prometheus默认的全局注册表,而是创建一个仅包含自定义指标的专属注册表,具体步骤如下:
- 创建自定义Prometheus注册表实例
- 将你的自定义CounterVec注册到这个专属注册表
- 使用
promhttp.HandlerFor替代默认的promhttp.Handler(),指定使用自定义注册表
- 使用
完整代码示例
import ( "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) // 创建仅用于自定义指标的注册表 var customRegistry = prometheus.NewRegistry() // 定义自定义CounterVec var Exchange = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "requests", Help: "show the requests id", }, []string{"requests"}) func init() { // 将指标注册到自定义注册表,而非全局默认注册表 customRegistry.MustRegister(Exchange) } // 配置/metrics端点 func main() { // ... 你的其他路由配置 ... // 使用HandlerFor指定自定义注册表 wr.router.Handle(urlMatrix, promhttp.HandlerFor(customRegistry, promhttp.HandlerOpts{ // 可选:根据需求配置,比如禁用响应压缩、设置错误日志等 })).Methods(http.MethodGet) // ... 启动服务 ... }
原理说明
默认的promhttp.Handler()会使用prometheus.DefaultRegisterer,这个全局注册表自动包含了Go运行时指标(以go_开头)、promhttp自身的指标(以promhttp_开头)。通过创建独立的自定义注册表,只注册我们需要的指标,就能确保/metrics端点仅返回自定义内容。
内容的提问来源于stack exchange,提问作者Elias Salom
相关产品推荐
相关产品推荐

