go-zero/core/metric/gauge.go

88 lines
1.7 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"
2020-07-26 17:09:05 +08:00
)
type (
// GaugeVecOpts is an alias of VectorOpts.
2020-07-26 17:09:05 +08:00
GaugeVecOpts VectorOpts
2021-02-23 13:53:19 +08:00
// GaugeVec represents a gauge vector.
GaugeVec interface {
// Set sets v to labels.
2020-07-26 17:09:05 +08:00
Set(v float64, labels ...string)
// Inc increments labels.
2020-07-26 17:09:05 +08:00
Inc(labels ...string)
// Dec decrements labels.
Dec(labels ...string)
// Add adds v to labels.
2020-07-26 17:09:05 +08:00
Add(v float64, labels ...string)
// Sub subtracts v to labels.
Sub(v float64, labels ...string)
2020-07-26 17:09:05 +08:00
close() bool
}
2021-05-04 21:33:08 +08:00
promGaugeVec struct {
2020-07-26 17:09:05 +08:00
gauge *prom.GaugeVec
}
)
// NewGaugeVec returns a GaugeVec.
func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec {
2020-07-26 17:09:05 +08:00
if cfg == nil {
return nil
}
vec := prom.NewGaugeVec(prom.GaugeOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
}, cfg.Labels)
2020-07-26 17:09:05 +08:00
prom.MustRegister(vec)
2021-05-04 21:33:08 +08:00
gv := &promGaugeVec{
2020-07-26 17:09:05 +08:00
gauge: vec,
}
proc.AddShutdownListener(func() {
gv.close()
})
return gv
}
func (gv *promGaugeVec) Add(v float64, labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Add(v)
})
2020-07-26 17:09:05 +08:00
}
func (gv *promGaugeVec) Dec(labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Dec()
})
}
func (gv *promGaugeVec) Inc(labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Inc()
})
}
func (gv *promGaugeVec) Set(v float64, labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Set(v)
})
2020-07-26 17:09:05 +08:00
}
func (gv *promGaugeVec) Sub(v float64, labels ...string) {
update(func() {
gv.gauge.WithLabelValues(labels...).Sub(v)
})
2020-07-26 17:09:05 +08:00
}
2021-05-04 21:33:08 +08:00
func (gv *promGaugeVec) close() bool {
2020-07-26 17:09:05 +08:00
return prom.Unregister(gv.gauge)
}