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