github.com/shuguocloud/go-zero@v1.3.0/core/metric/histogram.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 // A HistogramVecOpts is a histogram vector options. 10 HistogramVecOpts struct { 11 Namespace string 12 Subsystem string 13 Name string 14 Help string 15 Labels []string 16 Buckets []float64 17 } 18 19 // A HistogramVec interface represents a histogram vector. 20 HistogramVec interface { 21 // Observe adds observation v to labels. 22 Observe(v int64, labels ...string) 23 close() bool 24 } 25 26 promHistogramVec struct { 27 histogram *prom.HistogramVec 28 } 29 ) 30 31 // NewHistogramVec returns a HistogramVec. 32 func NewHistogramVec(cfg *HistogramVecOpts) HistogramVec { 33 if cfg == nil { 34 return nil 35 } 36 37 vec := prom.NewHistogramVec(prom.HistogramOpts{ 38 Namespace: cfg.Namespace, 39 Subsystem: cfg.Subsystem, 40 Name: cfg.Name, 41 Help: cfg.Help, 42 Buckets: cfg.Buckets, 43 }, cfg.Labels) 44 prom.MustRegister(vec) 45 hv := &promHistogramVec{ 46 histogram: vec, 47 } 48 proc.AddShutdownListener(func() { 49 hv.close() 50 }) 51 52 return hv 53 } 54 55 func (hv *promHistogramVec) Observe(v int64, labels ...string) { 56 hv.histogram.WithLabelValues(labels...).Observe(float64(v)) 57 } 58 59 func (hv *promHistogramVec) close() bool { 60 return prom.Unregister(hv.histogram) 61 }