Class: Rack::Instrument

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/instrument.rb

Defined Under Namespace

Classes: NullInstrument

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, instrument, instrumentations = []) ⇒ Instrument

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



14
15
16
17
18
19
20
21
# 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

Instance Attribute Details

#instrumentObject

Returns the value of attribute instrument.



23
24
25
# File 'lib/rack/instrument.rb', line 23

def instrument
  @instrument
end

#instrument_pathObject (readonly)

Flag for whether or not specific paths should be counted.



32
33
34
# File 'lib/rack/instrument.rb', line 32

def instrument_path
  @instrument_path
end

#instrument_requestObject (readonly)

Flag for whether or not requests should be counted.



26
27
28
# File 'lib/rack/instrument.rb', line 26

def instrument_request
  @instrument_request
end

#instrument_timeObject (readonly)

Flag for whether or not requests should be timed.



29
30
31
# File 'lib/rack/instrument.rb', line 29

def instrument_time
  @instrument_time
end

Instance Method Details

#call(env) ⇒ Object

Rack



35
36
37
38
39
40
41
42
43
44
45
46
# 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) ⇒ Object

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



66
67
68
69
70
71
72
73
74
75
76
77
# 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_requestObject

Count the total number of requests.



49
50
51
52
53
# File 'lib/rack/instrument.rb', line 49

def record_request
  return unless instrument_request

  instrument.increment 'requests'
end

#record_time(request_start) ⇒ Object

Instrument the total request time.



56
57
58
59
60
61
62
63
# 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