forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 1
/
counter.go
63 lines (53 loc) · 1.2 KB
/
counter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package metric
import (
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
)
type (
// A CounterVecOpts is an alias of VectorOpts.
CounterVecOpts VectorOpts
// CounterVec interface represents a counter vector.
CounterVec interface {
// Inc increments labels.
Inc(labels ...string)
// Add adds labels with v.
Add(v float64, labels ...string)
close() bool
}
promCounterVec struct {
counter *prom.CounterVec
}
)
// NewCounterVec returns a CounterVec.
func NewCounterVec(cfg *CounterVecOpts) CounterVec {
if cfg == nil {
return nil
}
vec := prom.NewCounterVec(prom.CounterOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
}, cfg.Labels)
prom.MustRegister(vec)
cv := &promCounterVec{
counter: vec,
}
proc.AddShutdownListener(func() {
cv.close()
})
return cv
}
func (cv *promCounterVec) Add(v float64, labels ...string) {
update(func() {
cv.counter.WithLabelValues(labels...).Add(v)
})
}
func (cv *promCounterVec) Inc(labels ...string) {
update(func() {
cv.counter.WithLabelValues(labels...).Inc()
})
}
func (cv *promCounterVec) close() bool {
return prom.Unregister(cv.counter)
}