Class: LHC::Prometheus

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

Constant Summary collapse

REQUEST_COUNTER_KEY =
:lhc_requests
REQUEST_HISTOGRAM_KEY =
:lhc_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_raw_request, #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/lhc/interceptors/prometheus.rb', line 15

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

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

Class Attribute Details

.registeredObject

Returns the value of attribute registered.



12
13
14
# File 'lib/lhc/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/lhc/interceptors/prometheus.rb', line 29

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

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

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

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