我正在试着写一个暴露普罗米修斯指标的程序。这是一个简单的程序,每次在我的struct上调用我的"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))
}每次我尝试递增计数器时,上面的代码都会失败,并显示“继续失败-访问错误”错误。即在这条线上
s.errorCount.Inc()我无法确定为什么计数器突然从内存中消失(如果我正确理解了错误消息)。我正在确定我是否遗漏了一些基本的东西。Go,或者我错误地使用了prometheus客户端库。
发布于 2020-03-06 06:31:25
在initialise()中,s是通过值传递的,这意味着在main()中,s.errorCount是nil。
只需更改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{}
}https://stackoverflow.com/questions/60552935
复制相似问题