Skip to content

Commit

Permalink
Apply default buckets in Prometheus Factory (#90)
Browse files Browse the repository at this point in the history
Signed-off-by: Konstantinos Moraitis <[email protected]>

Co-authored-by: Yuri Shkuro <[email protected]>
  • Loading branch information
moraitisk and yurishkuro authored Mar 29, 2021
1 parent 1d973d9 commit 2f0f6fe
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
10 changes: 9 additions & 1 deletion metrics/prometheus/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down Expand Up @@ -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"
Expand Down
21 changes: 21 additions & 0 deletions metrics/prometheus/factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 2f0f6fe

Please sign in to comment.