class Rack::Instrument

Attributes

instrument[RW]
instrument_path[R]

Flag for whether or not specific paths should be counted.

instrument_request[R]

Flag for whether or not requests should be counted.

instrument_time[R]

Flag for whether or not requests should be timed.

Public Class Methods

new(app, instrument, instrumentations = []) click to toggle source

use Rack::Instrument, Statsd.new(‘localhost’), [:request, :time, :path]

# File lib/rack/instrument.rb, line 14
def initialize(app, instrument, instrumentations = [])
  @app = app
  @instrument = instrument || NullInstrument.new

  @instrument_request = instrumentations.include? :request
  @instrument_time    = instrumentations.include? :time
  @instrument_path    = instrumentations.include? :path
end

Public Instance Methods

call(env) click to toggle source

Rack

# File lib/rack/instrument.rb, line 35
def call(env)
  request_start = Time.now

  record_request
  record_path(env)

  status, headers, response = @app.call(env)

  record_time(request_start)

  [status, headers, response]
end
record_path(env) click to toggle source

Count the number of times a specific path has been visited.

# File lib/rack/instrument.rb, line 66
def record_path(env)
  return unless instrument_path

  # Normalize and remove leading /
  path = env['REQUEST_PATH'].downcase.slice(1..-1)

  # Convert / to _
  path_key = path.gsub('/', '_').gsub('.', '_')
  path_key = 'index' if path_key.empty?

  instrument.increment 'requests.' + path_key
end
record_request() click to toggle source

Count the total number of requests.

# File lib/rack/instrument.rb, line 49
def record_request
  return unless instrument_request

  instrument.increment 'requests'
end
record_time(request_start) click to toggle source

Instrument the total request time.

# File lib/rack/instrument.rb, line 56
def record_time(request_start)
  return unless instrument_time

  request_end  = Time.now
  request_time = (request_end - request_start) * 1000

  instrument.timing 'request_time', request_time
end