Prometheus计数器:如何使用golang客户端获取当前值?

I am using counters to count the number of requests. Is there any way to get current value of a prometheus counter?

My aim is to reuse existing counter without allocating another variable.

Golang prometheus client version is 1.1.0.

Currently there is no way to get the value of a counter in the official Golang implementation.

You can also avoid double counting by incrementing your own counter and use an CounterFunc to collect it.

Note: use integral type and atomic to avoid concurrent access issues

// declare the counter as unsigned int
var requestsCounter uint64 = 0

// register counter in Prometheus collector
prometheus.MustRegister(prometheus.NewCounterFunc(
    prometheus.CounterOpts{
        Name: "requests_total",
        Help: "Counts number of requests",
    },
    func() float64 {
        return float64(atomic.LoadUint64(&requestsCounter))
    }))

// somewhere in your code
atomic.AddUint64(&requestsCounter, 1)