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/histogram.go

74 lines
1.6 KiB
Go

4 years ago
package metric
import (
prom "github.com/prometheus/client_golang/prometheus"
"github.com/zeromicro/go-zero/core/proc"
4 years ago
)
type (
// A HistogramVecOpts is a histogram vector options.
4 years ago
HistogramVecOpts struct {
Namespace string
Subsystem string
Name string
Help string
Labels []string
Buckets []float64
ConstLabels map[string]string
4 years ago
}
// A HistogramVec interface represents a histogram vector.
4 years ago
HistogramVec interface {
// Observe adds observation v to labels.
Observe(v int64, labels ...string)
// ObserveFloat allow to observe float64 values.
ObserveFloat(v float64, labels ...string)
4 years ago
close() bool
}
promHistogramVec struct {
histogram *prom.HistogramVec
}
)
// NewHistogramVec returns a HistogramVec.
4 years ago
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,
ConstLabels: cfg.ConstLabels,
4 years ago
}, 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))
})
4 years ago
}
func (hv *promHistogramVec) ObserveFloat(v float64, labels ...string) {
update(func() {
hv.histogram.WithLabelValues(labels...).Observe(v)
})
}
4 years ago
func (hv *promHistogramVec) close() bool {
return prom.Unregister(hv.histogram)
}