go-zero/core/metric/histogram.go

67 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 HistogramVecOpts is a histogram vector options.
2020-07-26 17:09:05 +08:00
HistogramVecOpts struct {
Namespace string
Subsystem string
Name string
Help string
Labels []string
Buckets []float64
}
// A HistogramVec interface represents a histogram vector.
2020-07-26 17:09:05 +08:00
HistogramVec interface {
// Observe adds observation v to labels.
2021-05-04 21:33:08 +08:00
Observe(v int64, labels ...string)
2020-07-26 17:09:05 +08:00
close() bool
}
promHistogramVec struct {
histogram *prom.HistogramVec
}
)
// NewHistogramVec returns a HistogramVec.
2020-07-26 17:09:05 +08:00
func NewHistogramVec(cfg *HistogramVecOpts) HistogramVec {
if cfg == nil {
return nil
}
vec := prom.NewHistogramVec(prom.HistogramOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
Buckets: cfg.Buckets,
}, cfg.Labels)
prom.MustRegister(vec)
hv := &promHistogramVec{
histogram: vec,
}
proc.AddShutdownListener(func() {
hv.close()
})
return hv
}
func (hv *promHistogramVec) Observe(v int64, labels ...string) {
if !prometheus.Enabled() {
return
}
2020-07-26 17:09:05 +08:00
hv.histogram.WithLabelValues(labels...).Observe(float64(v))
}
func (hv *promHistogramVec) close() bool {
return prom.Unregister(hv.histogram)
}