From 844e451baffecba5785197b76c4bfafc70fcca16 Mon Sep 17 00:00:00 2001 From: Lawrence Jones Date: Tue, 14 Jan 2020 09:49:07 +0000 Subject: [PATCH] Histogram bucket helpers Most client libraries provide helpers for generating linear/exponential histogram buckets. This provides the same interface as the golang client. Signed-off-by: Lawrence Jones --- README.md | 5 +++++ lib/prometheus/client/histogram.rb | 8 ++++++++ spec/prometheus/client/histogram_spec.rb | 14 ++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/README.md b/README.md index 64062e48..f7db15a8 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,11 @@ histogram.get(labels: { service: 'users' }) # => { 0.005 => 3, 0.01 => 15, 0.025 => 18, ..., 2.5 => 42, 5 => 42, 10 = >42 } ``` +Histograms provide default buckets of `[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]` + +You can specify your own buckets, either explicitly, or using the `Histogram.linear_buckets` +or `Histogram.exponential_buckets` methods to define regularly spaced buckets. + ### Summary Summary, similar to histograms, is an accumulator for samples. It captures diff --git a/lib/prometheus/client/histogram.rb b/lib/prometheus/client/histogram.rb index 893282ef..e72c40dc 100644 --- a/lib/prometheus/client/histogram.rb +++ b/lib/prometheus/client/histogram.rb @@ -33,6 +33,14 @@ def initialize(name, store_settings: store_settings) end + def self.linear_buckets(start:, width:, count:) + count.times.map { |idx| start.to_f + idx * width } + end + + def self.exponential_buckets(start:, factor: 2, count:) + count.times.map { |idx| start.to_f * factor ** idx } + end + def with_labels(labels) self.class.new(name, docstring: docstring, diff --git a/spec/prometheus/client/histogram_spec.rb b/spec/prometheus/client/histogram_spec.rb index c64c6218..d4e9da2a 100644 --- a/spec/prometheus/client/histogram_spec.rb +++ b/spec/prometheus/client/histogram_spec.rb @@ -37,6 +37,20 @@ end end + describe ".linear_buckets" do + it "generates buckets" do + expect(described_class.linear_buckets(start: 1, width: 2, count: 5)). + to eql([1.0, 3.0, 5.0, 7.0, 9.0]) + end + end + + describe ".exponential_buckets" do + it "generates buckets" do + expect(described_class.exponential_buckets(start: 1, factor: 2, count: 5)). + to eql([1.0, 2.0, 4.0, 8.0, 16.0]) + end + end + describe '#observe' do it 'records the given value' do expect do