feat: add metrics (#3624)

This commit is contained in:
MarkJoyMa
2023-10-26 23:51:28 +08:00
committed by GitHub
parent 199e86050e
commit c05e03bb5a
14 changed files with 759 additions and 29 deletions

View File

@@ -8,18 +8,21 @@ import (
type (
// A HistogramVecOpts is a histogram vector options.
HistogramVecOpts struct {
Namespace string
Subsystem string
Name string
Help string
Labels []string
Buckets []float64
Namespace string
Subsystem string
Name string
Help string
Labels []string
Buckets []float64
ConstLabels map[string]string
}
// A HistogramVec interface represents a histogram vector.
HistogramVec interface {
// Observe adds observation v to labels.
Observe(v int64, labels ...string)
// ObserveFloat allow to observe float64 values.
ObserveFloat(v float64, labels ...string)
close() bool
}
@@ -35,11 +38,12 @@ func NewHistogramVec(cfg *HistogramVecOpts) HistogramVec {
}
vec := prom.NewHistogramVec(prom.HistogramOpts{
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
Buckets: cfg.Buckets,
Namespace: cfg.Namespace,
Subsystem: cfg.Subsystem,
Name: cfg.Name,
Help: cfg.Help,
Buckets: cfg.Buckets,
ConstLabels: cfg.ConstLabels,
}, cfg.Labels)
prom.MustRegister(vec)
hv := &promHistogramVec{
@@ -58,6 +62,12 @@ func (hv *promHistogramVec) Observe(v int64, labels ...string) {
})
}
func (hv *promHistogramVec) ObserveFloat(v float64, labels ...string) {
update(func() {
hv.histogram.WithLabelValues(labels...).Observe(v)
})
}
func (hv *promHistogramVec) close() bool {
return prom.Unregister(hv.histogram)
}

View File

@@ -14,7 +14,7 @@ func TestNewHistogramVec(t *testing.T) {
Help: "rpc server requests duration(ms).",
Buckets: []float64{1, 2, 3},
})
defer histogramVec.close()
defer histogramVec.(*promHistogramVec).close()
histogramVecNil := NewHistogramVec(nil)
assert.NotNil(t, histogramVec)
assert.Nil(t, histogramVecNil)
@@ -28,9 +28,10 @@ func TestHistogramObserve(t *testing.T) {
Buckets: []float64{1, 2, 3},
Labels: []string{"method"},
})
defer histogramVec.close()
defer histogramVec.(*promHistogramVec).close()
hv, _ := histogramVec.(*promHistogramVec)
hv.Observe(2, "/Users")
hv.ObserveFloat(1.1, "/Users")
metadata := `
# HELP counts rpc server requests duration(ms).
@@ -38,11 +39,11 @@ func TestHistogramObserve(t *testing.T) {
`
val := `
counts_bucket{method="/Users",le="1"} 0
counts_bucket{method="/Users",le="2"} 1
counts_bucket{method="/Users",le="3"} 1
counts_bucket{method="/Users",le="+Inf"} 1
counts_sum{method="/Users"} 2
counts_count{method="/Users"} 1
counts_bucket{method="/Users",le="2"} 2
counts_bucket{method="/Users",le="3"} 2
counts_bucket{method="/Users",le="+Inf"} 2
counts_sum{method="/Users"} 3.1
counts_count{method="/Users"} 2
`
err := testutil.CollectAndCompare(hv.histogram, strings.NewReader(metadata+val))