go-zero/core/metric/histogram.go

74 lines
1.6 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 (
// A HistogramVecOpts is a histogram vector options.
2020-07-26 17:09:05 +08:00
HistogramVecOpts struct {
2023-10-26 23:51:28 +08:00
Namespace string
Subsystem string
Name string
Help string
Labels []string
Buckets []float64
ConstLabels map[string]string
2020-07-26 17:09:05 +08:00
}
// 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)
2023-10-26 23:51:28 +08:00
// ObserveFloat allow to observe float64 values.
ObserveFloat(v float64, 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{
2023-10-26 23:51:28 +08:00
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
Buckets: cfg.Buckets,
ConstLabels: cfg.ConstLabels,
2020-07-26 17:09:05 +08:00
}, cfg.Labels)
prom.MustRegister(vec)
hv := &promHistogramVec{
histogram: vec,
}
proc.AddShutdownListener(func() {
hv.close()
})
return hv
}
func (hv *promHistogramVec) Observe(v int64, labels ...string) {
update(func() {
hv.histogram.WithLabelValues(labels...).Observe(float64(v))
})
2020-07-26 17:09:05 +08:00
}
2023-10-26 23:51:28 +08:00
func (hv *promHistogramVec) ObserveFloat(v float64, labels ...string) {
update(func() {
hv.histogram.WithLabelValues(labels...).Observe(v)
})
}
2020-07-26 17:09:05 +08:00
func (hv *promHistogramVec) close() bool {
return prom.Unregister(hv.histogram)
}