Class: DHC::Prometheus

Inherits:
Interceptor show all
Includes:
ActiveSupport::Configurable
Defined in:
lib/dhc/interceptors/prometheus.rb

Constant Summary collapse

REQUEST_COUNTER_KEY =
:dhc_requests
REQUEST_HISTOGRAM_KEY =
:dhc_request_seconds

Class Attribute Summary collapse

Attributes inherited from Interceptor

#request

Instance Method Summary collapse

Methods inherited from Interceptor

#after_request, #all_interceptor_classes, #before_init, #before_request, #before_response, dup, #response

Constructor Details

#initialize(request) ⇒ Prometheus

Returns a new instance of Prometheus.



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/dhc/interceptors/prometheus.rb', line 15

def initialize(request)
  super(request)
  return if DHC::Prometheus.registered || DHC::Prometheus.client.blank?

  begin
    DHC::Prometheus.client.registry.counter(DHC::Prometheus::REQUEST_COUNTER_KEY, 'Counter of all DHC requests.')
    DHC::Prometheus.client.registry.histogram(DHC::Prometheus::REQUEST_HISTOGRAM_KEY, 'Request timings for all DHC requests in seconds.')
  rescue Prometheus::Client::Registry::AlreadyRegisteredError => e
    Rails.logger.error(e) if defined?(Rails)
  ensure
    DHC::Prometheus.registered = true
  end
end

Class Attribute Details

.registeredObject

Returns the value of attribute registered.



12
13
14
# File 'lib/dhc/interceptors/prometheus.rb', line 12

def registered
  @registered
end

Instance Method Details

#after_responseObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dhc/interceptors/prometheus.rb', line 29

def after_response
  return if !DHC::Prometheus.registered || DHC::Prometheus.client.blank?

  host = URI.parse(request.url).host

  DHC::Prometheus.client.registry
    .get(DHC::Prometheus::REQUEST_COUNTER_KEY)
    .increment(
      code: response.code,
      success: response.success?,
      timeout: response.timeout?,
      host: host,
      app: DHC::Prometheus.namespace
    )

  DHC::Prometheus.client.registry
    .get(DHC::Prometheus::REQUEST_HISTOGRAM_KEY)
    .observe({
               host: host,
               app: DHC::Prometheus.namespace
             }, response.time)
end