Class: RequestLog::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/request_log/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



3
4
5
6
7
8
9
# File 'lib/request_log/middleware.rb', line 3

def initialize(app, options = {})
  @app = app
  @logger = options[:logger] || lambda { |data| ::RequestLog::Db.requests.insert(data.attributes) }
  @profiler = options[:profiler] || ::RequestLog::Profiler
  @timeout = options[:timeout] || 0.3
  @only_path = options[:only_path]
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/request_log/middleware.rb', line 11

def call(env)
  app_start = Time.now 
  rack_response = @app.call(env)
  app_time = Time.now - app_start
  return rack_response unless should_log?(env)
  begin
    logger_start = Time.now
    Timeout::timeout(@timeout) do
      @logger.call(::RequestLog::Data.new(env, rack_response, app_time))
    end
    @profiler.call(:result => :success, :elapsed_time => (Time.now - logger_start))
  rescue Exception => e
    @profiler.call(:result => :failure, :exception => e)
    $stderr.puts("#{self.class}: exception #{e} #{e.backtrace.join("\n")}")
  ensure
    return rack_response  
  end
end