Class: NatsWork::Monitoring::PrometheusExporter

Inherits:
Object
  • Object
show all
Defined in:
lib/natswork/monitoring.rb

Overview

Prometheus metrics exporter

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ PrometheusExporter

Returns a new instance of PrometheusExporter.



10
11
12
13
14
15
# File 'lib/natswork/monitoring.rb', line 10

def initialize(options = {})
  @metrics = options[:metrics] || Metrics.global
  @port = options[:port] || 9090
  @path = options[:path] || '/metrics'
  @server = nil
end

Instance Method Details

#export_metricsObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/natswork/monitoring.rb', line 38

def export_metrics
  lines = []
  snapshot = @metrics.snapshot

  # Export counters
  snapshot[:counters].each do |metric, value|
    name, labels = parse_metric_name(metric)
    lines << "# TYPE natswork_#{name} counter"
    lines << "natswork_#{name}#{format_labels(labels)} #{value}"
  end

  # Export gauges
  snapshot[:gauges].each do |metric, value|
    name, labels = parse_metric_name(metric)
    lines << "# TYPE natswork_#{name} gauge"
    lines << "natswork_#{name}#{format_labels(labels)} #{value}"
  end

  # Export histograms
  snapshot[:histograms].each do |metric, stats|
    next unless stats

    name, labels = parse_metric_name(metric)
    lines << "# TYPE natswork_#{name} histogram"
    lines << "natswork_#{name}_count#{format_labels(labels)} #{stats[:count]}"
    lines << "natswork_#{name}_sum#{format_labels(labels)} #{stats[:count] * stats[:mean]}"

    # Add percentiles as separate metrics
    %w[50 95 99].each do |percentile|
      pct_key = "p#{percentile}".to_sym
      if stats[pct_key]
        lines << "natswork_#{name}_percentile#{format_labels(labels.merge(percentile: percentile))} #{stats[pct_key]}"
      end
    end
  end

  "#{lines.join("\n")}\n"
end

#start_serverObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/natswork/monitoring.rb', line 17

def start_server
  require 'webrick'

  @server = WEBrick::HTTPServer.new(
    Port: @port,
    Logger: WEBrick::Log.new('/dev/null'),
    AccessLog: []
  )

  @server.mount_proc(@path) do |_req, res|
    res['Content-Type'] = 'text/plain'
    res.body = export_metrics
  end

  Thread.new { @server.start }
end

#stop_serverObject



34
35
36
# File 'lib/natswork/monitoring.rb', line 34

def stop_server
  @server&.shutdown
end