首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >普罗米修斯客户端过早清理计数器?

普罗米修斯客户端过早清理计数器?
EN

Stack Overflow用户
提问于 2020-03-06 03:47:41
回答 1查看 104关注 0票数 0

我正在试着写一个暴露普罗米修斯指标的程序。这是一个简单的程序,每次在我的struct上调用我的"run“方法时,我想要递增一个计数器。

代码语言:javascript
复制
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))
}

每次我尝试递增计数器时,上面的代码都会失败,并显示“继续失败-访问错误”错误。即在这条线上

代码语言:javascript
复制
s.errorCount.Inc()

我无法确定为什么计数器突然从内存中消失(如果我正确理解了错误消息)。我正在确定我是否遗漏了一些基本的东西。Go,或者我错误地使用了prometheus客户端库。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-06 06:31:25

initialise()中,s是通过值传递的,这意味着在main()中,s.errorCountnil

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

代码语言:javascript
复制
func (s *myStruct) initialize() {
...

下面是几个你可能想试试的建议:

代码语言:javascript
复制
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{}
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60552935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档