Class: PrometheusReporter::TextFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/prometheus_reporter/text_formatter.rb

Constant Summary collapse

TYPES =
%i[counter gauge histogram summary untyped].freeze
LABELESS =
:labeless
HELP_TOKEN =
:help
TYPE_TOKEN =
:type
DEFAULTS =
{ HELP_TOKEN => nil, TYPE_TOKEN => nil }.freeze
TOKENS =
[HELP_TOKEN, TYPE_TOKEN].freeze
SEPARATOR =
"\n"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prefix: PrometheusReporter.config.prefix) ⇒ TextFormatter

Returns a new instance of TextFormatter.



21
22
23
24
# File 'lib/prometheus_reporter/text_formatter.rb', line 21

def initialize(prefix: PrometheusReporter.config.prefix)
  @data = {}
  @prefix = prefix
end

Class Method Details

.draw(prefix: PrometheusReporter.config.prefix, &block) ⇒ Object



14
15
16
17
18
# File 'lib/prometheus_reporter/text_formatter.rb', line 14

def draw(prefix: PrometheusReporter.config.prefix, &block)
  formatter = new(prefix: prefix)
  formatter.instance_eval(&block)
  formatter.to_s
end

Instance Method Details

#entry(key, value:, labels: {}, timestamp: nil) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/prometheus_reporter/text_formatter.rb', line 37

def entry(key, value:, labels: {}, timestamp: nil)
  @data[prefixed(key)] ||= DEFAULTS.dup

  label_key = labels.any? ? labels : LABELESS
  entry_data =
    {
      value:     value,
      timestamp: timestamp
    }.compact

  @data[prefixed(key)][label_key] = entry_data
end

#help(key, description) ⇒ Object



26
27
28
# File 'lib/prometheus_reporter/text_formatter.rb', line 26

def help(key, description)
  set_token_value!(HELP_TOKEN, key, description)
end

#to_sObject



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/prometheus_reporter/text_formatter.rb', line 50

def to_s
  metrics_data = []

  sort_hash(@data).each do |prometheus_key_name, prometheus_key_values|
    prometheus_key_values = prometheus_key_values.compact
    validate_data!(prometheus_key_name, prometheus_key_values)
    metrics_data << metric_entry(prometheus_key_name, prometheus_key_values)
  end

  metrics_data.join(SEPARATOR)
end

#type(key, type) ⇒ Object

Raises:



30
31
32
33
34
35
# File 'lib/prometheus_reporter/text_formatter.rb', line 30

def type(key, type)
  type = type.downcase.to_sym
  raise(UnknownMetricType, type) unless TYPES.include?(type)

  set_token_value!(TYPE_TOKEN, key, type)
end