go - Prometheus客户过早清理柜台?

标签 go prometheus

我正在尝试编写一个程序,该程序公开了普罗米修斯的度量标准。
这是一个简单的程序,我想在结构上每次调用“运行”方法时都增加一个计数器。


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))
}

每次我尝试递增计数器时,以上代码都会失败,并显示“无法继续-错误的访问”错误。即在这一行
s.errorCount.Inc()

我无法确定为什么计数器突然从内存中消失(如果我正确理解了错误消息)。
我确定我是否缺少基本的东西去吧,还是我使用Prometheus客户端库不正确。

最佳答案

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{}
}

关于go - Prometheus客户过早清理柜台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60552935/

相关文章:

go - 将值设置为继承字段

go - 什么时候在 golang 中使用劫持?

amazon-web-services - 如何将数组存储到 dynamoDB 表中

node.js - 有没有办法将 opentelemetry span 导出到 prometheus?

prometheus - rate() 函数如何平均请求持续时间?

go - 为什么在 go lang 中对关键字进行严格的代码格式

docker - 关于在 docker 容器中运行 Prometheus 有什么建议吗?

prometheus - 当天 Prometheus 指标的总和

elasticsearch - 在Prometheus警报规则的标签值中使用“今天”日期

go - 为什么 Golang 包必须是 v0 或 v1 而不是 v2020