Class: GitLab::Monitor::PrometheusMetrics

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab_monitor/prometheus.rb

Overview

Prometheus metrics container

Provides a simple API to ‘add` metrics and then turn them `to_s` which will just dump all the metrics in prometheus format

The add method also can take any arbitrary amount of labels in a ‘key: value` format.

Instance Method Summary collapse

Constructor Details

#initialize(include_timestamp: true) ⇒ PrometheusMetrics

Returns a new instance of PrometheusMetrics.



12
13
14
15
16
# File 'lib/gitlab_monitor/prometheus.rb', line 12

def initialize(include_timestamp: true)
  @metrics = Hash.new { |h, k| h[k] = [] }
  @quantiles = Hash.new { |h, k| h[k] = [] }
  @include_timestamp = include_timestamp
end

Instance Method Details

#add(name, value, quantile = false, **labels) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/gitlab_monitor/prometheus.rb', line 18

def add(name, value, quantile = false, **labels)
  if quantile
    @quantiles[{ name: name, labels: labels }] << value
  else
    @metrics[name] << { value: value, labels: labels, timestamp: (Time.now.to_f * 1000).to_i }
  end

  self
end

#to_sObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gitlab_monitor/prometheus.rb', line 28

def to_s
  add_quantiles_to_metrics

  buffer = ""
  @metrics.each do |name, measurements|
    measurements.each do |measurement|
      buffer << name.to_s
      labels = (measurement[:labels] || {}).map { |label, value| "#{label}=\"#{value}\"" }.join(",")
      buffer << "{#{labels}}" unless labels.empty?
      buffer << " #{measurement[:value]}"
      buffer << " #{measurement[:timestamp]}" if @include_timestamp
      buffer << "\n"
    end
  end
  buffer
end