小编Rin*_*ino的帖子

Golang Prometheus Exporter - 按需拉取指标

根据prometheus 文档中的定义,在编写导出器时,它声明以下内容:

仅当 Prometheus 抓取指标时才应从应用程序中提取指标,导出器不应根据自己的计时器执行抓取。

以下代码在技术上工作正常,并使用我的自定义指标发布适当的页面。所以它按原样解决了我的业务需求。

然而,它效率低下并且运行无限循环来不断更新值。这与上面提到的仅在 Prometheus 抓取时生成指标值的文档中的做法不符

package main

import (
    "log"
    "net/http"
    "time"

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

func main() {
    var metricSystemTime = prometheus.NewGauge(prometheus.GaugeOpts{
        Name: "custom_system_time", Help: "Timestamp in unix epoch format"})

    prometheus.MustRegister(metricSystemTime)

    go startServer()

    for {
        metricSystemTime.Set(float64(time.Now().Unix()))
        time.Sleep(1 * time.Second)
    }
}

func startServer() {
    http.Handle("/metrics", promhttp.Handler())
    log.Fatal(http.ListenAndServe(":19100", nil))
}

Run Code Online (Sandbox Code Playgroud)

为了仅在 prometheus 抓取导出器端点时提取指标,这意味着我需要以某种方式侦听对象上的 GET 请求http.ListenAndServe()?我怎样才能做到这一点?

在我的阅读中,我发现http.HandlerFunc()相反,http.Handler()它似乎走在正确的道路上,但我无法让它工作promhttp.Handler(),而且我在其中迷失了方向。

go prometheus

2
推荐指数
1
解决办法
1841
查看次数

标签 统计

go ×1

prometheus ×1