github.com/shuguocloud/go-zero@v1.3.0/core/metric/counter.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 CounterVecOpts is an alias of VectorOpts.
    10  	CounterVecOpts VectorOpts
    11  
    12  	// CounterVec interface represents a counter vector.
    13  	CounterVec interface {
    14  		// Inc increments labels.
    15  		Inc(labels ...string)
    16  		// Add adds labels with v.
    17  		Add(v float64, labels ...string)
    18  		close() bool
    19  	}
    20  
    21  	promCounterVec struct {
    22  		counter *prom.CounterVec
    23  	}
    24  )
    25  
    26  // NewCounterVec returns a CounterVec.
    27  func NewCounterVec(cfg *CounterVecOpts) CounterVec {
    28  	if cfg == nil {
    29  		return nil
    30  	}
    31  
    32  	vec := prom.NewCounterVec(prom.CounterOpts{
    33  		Namespace: cfg.Namespace,
    34  		Subsystem: cfg.Subsystem,
    35  		Name:      cfg.Name,
    36  		Help:      cfg.Help,
    37  	}, cfg.Labels)
    38  	prom.MustRegister(vec)
    39  	cv := &promCounterVec{
    40  		counter: vec,
    41  	}
    42  	proc.AddShutdownListener(func() {
    43  		cv.close()
    44  	})
    45  
    46  	return cv
    47  }
    48  
    49  func (cv *promCounterVec) Inc(labels ...string) {
    50  	cv.counter.WithLabelValues(labels...).Inc()
    51  }
    52  
    53  func (cv *promCounterVec) Add(v float64, labels ...string) {
    54  	cv.counter.WithLabelValues(labels...).Add(v)
    55  }
    56  
    57  func (cv *promCounterVec) close() bool {
    58  	return prom.Unregister(cv.counter)
    59  }