From a1f673009dd3872067a92553a423ac415637663f Mon Sep 17 00:00:00 2001 From: Konstantinos Moraitis Date: Mon, 29 Mar 2021 12:13:20 +0300 Subject: [PATCH] Apply default buckets in Prometheus Factory Signed-off-by: Konstantinos Moraitis --- metrics/prometheus/factory.go | 10 +++++++++- metrics/prometheus/factory_test.go | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/metrics/prometheus/factory.go b/metrics/prometheus/factory.go index 44205bc..2e5d49c 100644 --- a/metrics/prometheus/factory.go +++ b/metrics/prometheus/factory.go @@ -197,12 +197,13 @@ func (f *Factory) Histogram(options metrics.HistogramOptions) metrics.Histogram help = options.Name } name := f.subScope(options.Name) + buckets := f.selectBuckets(options.Buckets) tags := f.mergeTags(options.Tags) labelNames := f.tagNames(tags) opts := prometheus.HistogramOpts{ Name: name, Help: help, - Buckets: options.Buckets, + Buckets: buckets, } hv := f.cache.getOrMakeHistogramVec(opts, labelNames) return &histogram{ @@ -293,6 +294,13 @@ func (f *Factory) tagsAsLabelValues(labels []string, tags map[string]string) []s return ret } +func (f *Factory) selectBuckets(buckets []float64) []float64 { + if len(buckets) > 0 { + return buckets + } + return f.buckets +} + func counterNamingConvention(name string) string { if !strings.HasSuffix(name, "_total") { name += "_total" diff --git a/metrics/prometheus/factory_test.go b/metrics/prometheus/factory_test.go index cb03fe6..6e0d7fe 100644 --- a/metrics/prometheus/factory_test.go +++ b/metrics/prometheus/factory_test.go @@ -361,6 +361,27 @@ func TestHistogramCustomBuckets(t *testing.T) { assert.Len(t, m1.GetHistogram().GetBucket(), 1) } +func TestHistogramDefaultBuckets(t *testing.T) { + registry := prometheus.NewPedanticRegistry() + f1 := New(WithRegisterer(registry), WithBuckets([]float64{1.5})) + // dot and dash in the metric name will be replaced with underscore + t1 := f1.Histogram(metrics.HistogramOptions{ + Name: "bender.bending-rodriguez", + Tags: map[string]string{"x": "y"}, + Buckets: nil, + }) + t1.Record(1) + t1.Record(2) + + snapshot, err := registry.Gather() + require.NoError(t, err) + + m1 := findMetric(t, snapshot, "bender_bending_rodriguez", map[string]string{"x": "y"}) + assert.EqualValues(t, 2, m1.GetHistogram().GetSampleCount(), "%+v", m1) + assert.EqualValues(t, 3, m1.GetHistogram().GetSampleSum(), "%+v", m1) + assert.Len(t, m1.GetHistogram().GetBucket(), 1) +} + func findMetric(t *testing.T, snapshot []*promModel.MetricFamily, name string, tags map[string]string) *promModel.Metric { for _, mf := range snapshot { if mf.GetName() != name {