diff --git a/README.md b/README.md index fd17ce1a..27900ac7 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,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 29f540b6..795477f1 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 48aaa62a..780875f9 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