Class: PrometheusExporter::Metric::Histogram

Inherits:
Base
  • Object
show all
Defined in:
lib/prometheus_exporter/metric/histogram.rb

Constant Summary collapse

DEFAULT_BUCKETS =
[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5.0, 10.0].freeze

Instance Attribute Summary

Attributes inherited from Base

#data, #help, #name

Instance Method Summary collapse

Methods inherited from Base

default_labels, default_labels=, default_prefix, default_prefix=, #from_json, #labels_text, #prefix, #to_prometheus_text

Constructor Details

#initialize(name, help, opts = {}) ⇒ Histogram

Returns a new instance of Histogram.



8
9
10
11
12
# File 'lib/prometheus_exporter/metric/histogram.rb', line 8

def initialize(name, help, opts = {})
  super(name, help)
  @buckets = (opts[:buckets] || DEFAULT_BUCKETS).sort.reverse
  reset!
end

Instance Method Details

#ensure_histogram(labels) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/prometheus_exporter/metric/histogram.rb', line 54

def ensure_histogram(labels)
  @sums[labels] ||= 0.0
  @counts[labels] ||= 0
  buckets = @observations[labels]
  if buckets.nil?
    buckets = @buckets.map { |b| [b, 0] }.to_h
    @observations[labels] = buckets
  end
  buckets
end

#fill_buckets(value, buckets) ⇒ Object



65
66
67
68
69
70
# File 'lib/prometheus_exporter/metric/histogram.rb', line 65

def fill_buckets(value, buckets)
  @buckets.each do |b|
    break if value > b
    buckets[b] += 1
  end
end

#metric_textObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/prometheus_exporter/metric/histogram.rb', line 24

def metric_text
  text = +""
  first = true
  @observations.each do |labels, buckets|
    text << "\n" unless first
    first = false
    count = @counts[labels]
    sum = @sums[labels]
    text << "#{prefix(@name)}_bucket#{labels_text(with_bucket(labels, "+Inf"))} #{count}\n"
    @buckets.each do |bucket|
      value = @observations[labels][bucket]
      text << "#{prefix(@name)}_bucket#{labels_text(with_bucket(labels, bucket.to_s))} #{value}\n"
    end
    text << "#{prefix(@name)}_count#{labels_text(labels)} #{count}\n"
    text << "#{prefix(@name)}_sum#{labels_text(labels)} #{sum}"
  end
  text
end

#observe(value, labels = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/prometheus_exporter/metric/histogram.rb', line 43

def observe(value, labels = nil)
  labels ||= {}
  buckets = ensure_histogram(labels)

  value = value.to_f
  @sums[labels] += value
  @counts[labels] += 1

  fill_buckets(value, buckets)
end

#reset!Object



14
15
16
17
18
# File 'lib/prometheus_exporter/metric/histogram.rb', line 14

def reset!
  @sums = {}
  @counts = {}
  @observations = {}
end

#typeObject



20
21
22
# File 'lib/prometheus_exporter/metric/histogram.rb', line 20

def type
  "histogram"
end

#with_bucket(labels, bucket) ⇒ Object



72
73
74
# File 'lib/prometheus_exporter/metric/histogram.rb', line 72

def with_bucket(labels, bucket)
  labels.merge("le" => bucket)
end