普罗米修斯客户过早清理柜台?

Prometheus client cleaning up counter prematurely?

我正在尝试编写一个公开普罗米修斯指标的程序。 这是一个简单的程序,每次在我的结构上调用 "run" 方法时,我都想增加一个计数器。


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

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

type myStruct struct {
    errorCount prometheus.Counter
}

func (s myStruct) initialize() {
    s.errorCount = prometheus.NewCounter(prometheus.CounterOpts{
        Name: "my_counter",
        Help: "sample prometheus counter",
    })
}

func (s myStruct) run() {
    s.errorCount.Add(1)
}

func main() {
    s := new(myStruct)
    s.initialize()

    http.Handle("/metrics", promhttp.Handler())

    go func() {
        for {
            s.run()
            time.Sleep(time.Second)
        }
    }()

    log.Fatal(http.ListenAndServe(":8080", nil))
}

每次我尝试增加计数器时,上面的代码都失败并出现 "Failed to continue - bad access" 错误。即在这一行

s.errorCount.Inc()

我无法确定为什么计数器突然从内存中消失(如果我没有正确理解错误消息的话)。 我确定我是否遗漏了一些基本的东西 w.r.t。去吧,还是我prometheus客户端库用错了

In initialise() s 正在按值传递,这意味着 main() s.errorCountnil.

只需更改 initialise(和 run)的声明以获取指针。

func (s *myStruct) initialize() {
...

您可能还想尝试一些建议:

func init() {
    go func() {
        http.Handle("/metrics", promhttp.Handler())
        log.Fatal(http.ListenAndServe(":8080", nil))
    }()
}

type myStruct struct {
    errorCount prometheus.Counter
}

func NewMyStruct() *myStruct {
    return &myStruct {
        errorCount: prometheus.NewCounter(prometheus.CounterOpts {
            Name: "my_counter",
            Help: "sample prometheus counter",
        }),
    }
}

func (s *myStruct) run() {
    s.errorCount.Add(1)
}

func main() {
    s := NewMyStruct()

    go func() {
     for {
         s.run()
         time.Sleep(time.Second)
     }
    }()

    // ... OR select{}
}