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