You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/metric/gauge.go

80 lines
1.4 KiB
Go

4 years ago
package metric
import (
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/prometheus"
4 years ago
)
type (
// GaugeVecOpts is an alias of VectorOpts.
4 years ago
GaugeVecOpts VectorOpts
// GaugeVec represents a gauge vector.
GaugeVec interface {
// Set sets v to labels.
4 years ago
Set(v float64, labels ...string)
// Inc increments labels.
4 years ago
Inc(labels ...string)
// Add adds v to labels.
4 years ago
Add(v float64, labels ...string)
close() bool
}
promGaugeVec struct {
4 years ago
gauge *prom.GaugeVec
}
)
// NewGaugeVec returns a GaugeVec.
func NewGaugeVec(cfg *GaugeVecOpts) GaugeVec {
4 years ago
if cfg == nil {
return nil
}
vec := prom.NewGaugeVec(
prom.GaugeOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
}, cfg.Labels)
prom.MustRegister(vec)
gv := &promGaugeVec{
4 years ago
gauge: vec,
}
proc.AddShutdownListener(func() {
gv.close()
})
return gv
}
func (gv *promGaugeVec) Inc(labels ...string) {
if !prometheus.Enabled() {
return
}
4 years ago
gv.gauge.WithLabelValues(labels...).Inc()
}
func (gv *promGaugeVec) Add(v float64, labels ...string) {
if !prometheus.Enabled() {
return
}
gv.gauge.WithLabelValues(labels...).Add(v)
4 years ago
}
func (gv *promGaugeVec) Set(v float64, labels ...string) {
if !prometheus.Enabled() {
return
}
gv.gauge.WithLabelValues(labels...).Set(v)
4 years ago
}
func (gv *promGaugeVec) close() bool {
4 years ago
return prom.Unregister(gv.gauge)
}