Class: NurseAndrea::MetricsMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/nurse_andrea/metrics_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ MetricsMiddleware

Returns a new instance of MetricsMiddleware.



3
4
5
# File 'lib/nurse_andrea/metrics_middleware.rb', line 3

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/nurse_andrea/metrics_middleware.rb', line 7

def call(env)
  return @app.call(env) unless NurseAndrea.config.enabled? && NurseAndrea.config.valid?
  return @app.call(env) if env["PATH_INFO"]&.start_with?("/nurse_andrea")

  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  status, headers, body = @app.call(env)
  duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at) * 1000).round(2)

  NurseAndrea::MetricsShipper.instance.enqueue(
    name:      "http.server.duration",
    value:     duration_ms,
    unit:      "ms",
    timestamp: Time.now.utc.iso8601(3),
    tags: {
      service:     NurseAndrea.config.service_name,
      http_method: env["REQUEST_METHOD"],
      http_status: status.to_s,
      http_path:   normalize_path(env["PATH_INFO"])
    }.compact
  )

  [ status, headers, body ]
rescue => e
  warn "[NurseAndrea] Middleware error: #{e.message}" if NurseAndrea.config.debug
  raise
end