go-zero/core/metric/counter.go

69 lines
1.3 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package metric
import (
2022-09-17 20:06:23 +08:00
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/prometheus"
2020-07-26 17:09:05 +08:00
)
type (
// A CounterVecOpts is an alias of VectorOpts.
2020-07-26 17:09:05 +08:00
CounterVecOpts VectorOpts
// CounterVec interface represents a counter vector.
2020-07-26 17:09:05 +08:00
CounterVec interface {
// Inc increments labels.
2021-05-04 21:33:08 +08:00
Inc(labels ...string)
// Add adds labels with v.
2020-07-26 17:09:05 +08:00
Add(v float64, labels ...string)
close() bool
}
promCounterVec struct {
counter *prom.CounterVec
}
)
// NewCounterVec returns a CounterVec.
2020-07-26 17:09:05 +08:00
func NewCounterVec(cfg *CounterVecOpts) CounterVec {
if cfg == nil {
return nil
}
vec := prom.NewCounterVec(prom.CounterOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
}, cfg.Labels)
prom.MustRegister(vec)
cv := &promCounterVec{
counter: vec,
}
proc.AddShutdownListener(func() {
cv.close()
})
return cv
}
func (cv *promCounterVec) Inc(labels ...string) {
if !prometheus.Enabled() {
return
}
2020-07-26 17:09:05 +08:00
cv.counter.WithLabelValues(labels...).Inc()
}
2021-05-04 21:33:08 +08:00
func (cv *promCounterVec) Add(v float64, labels ...string) {
if !prometheus.Enabled() {
return
}
2021-05-04 21:33:08 +08:00
cv.counter.WithLabelValues(labels...).Add(v)
2020-07-26 17:09:05 +08:00
}
func (cv *promCounterVec) close() bool {
return prom.Unregister(cv.counter)
}