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