class StatsDRackInstrument

Attributes

app[R]

Public Class Methods

new(app) click to toggle source
# File lib/statsd_rack_instrument.rb, line 6
def initialize(app)
  @app = app
end

Protected Instance Methods

build_path(env) click to toggle source
# File lib/statsd_rack_instrument.rb, line 38
def build_path(env)
  strip_ids_from_path([env['SCRIPT_NAME'], env['PATH_INFO']].join)
end
observe(env) { || ... } click to toggle source
# File lib/statsd_rack_instrument.rb, line 16
def observe(env)
  time_t0 = Time.now
  response = yield
  duration = Time.now - time_t0

  tags = {
    code: response.first.to_s,
    method: env['REQUEST_METHOD'].downcase,
    path: build_path(env)
  }
  StatsD.histogram(
    'rack_server_request_duration_seconds', duration, tags: tags
  )

  response
rescue => e
  StatsD.increment(
    'rack_server_exceptions_total', tags: { exception: e.class.name }
  )
  raise
end
strip_ids_from_path(path) click to toggle source

inspired by github.com/prometheus/client_ruby/blob/v2.1.0/lib/prometheus/middleware/collector.rb#L88

# File lib/statsd_rack_instrument.rb, line 43
def strip_ids_from_path(path)
  path.gsub(
    %r{/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(/|$)},
    '/:uuid\\1'
  ).gsub(
    %r{/\d+(/|$)}, '/:id\\1'
  )
end