github.com/lingyao2333/mo-zero@v1.4.1/core/metric/gauge.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 // GaugeVecOpts is an alias of VectorOpts. 11 GaugeVecOpts VectorOpts 12 13 // GaugeVec represents a gauge vector. 14 GaugeVec interface { 15 // Set sets v to labels. 16 Set(v float64, labels ...string) 17 // Inc increments labels. 18 Inc(labels ...string) 19 // Add adds v to labels. 20 Add(v float64, labels ...string) 21 close() bool 22 } 23 24 promGaugeVec struct { 25 gauge *prom.GaugeVec 26 } 27 ) 28 29 // NewGaugeVec returns a GaugeVec. 30 func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec { 31 if cfg == nil { 32 return nil 33 } 34 35 vec := prom.NewGaugeVec( 36 prom.GaugeOpts{ 37 Namespace: cfg.Namespace, 38 Subsystem: cfg.Subsystem, 39 Name: cfg.Name, 40 Help: cfg.Help, 41 }, cfg.Labels) 42 prom.MustRegister(vec) 43 gv := &promGaugeVec{ 44 gauge: vec, 45 } 46 proc.AddShutdownListener(func() { 47 gv.close() 48 }) 49 50 return gv 51 } 52 53 func (gv *promGaugeVec) Inc(labels ...string) { 54 if !prometheus.Enabled() { 55 return 56 } 57 58 gv.gauge.WithLabelValues(labels...).Inc() 59 } 60 61 func (gv *promGaugeVec) Add(v float64, labels ...string) { 62 if !prometheus.Enabled() { 63 return 64 } 65 66 gv.gauge.WithLabelValues(labels...).Add(v) 67 } 68 69 func (gv *promGaugeVec) Set(v float64, labels ...string) { 70 if !prometheus.Enabled() { 71 return 72 } 73 74 gv.gauge.WithLabelValues(labels...).Set(v) 75 } 76 77 func (gv *promGaugeVec) close() bool { 78 return prom.Unregister(gv.gauge) 79 }