Skip to content

Instantly share code, notes, and snippets.

@dstrelau
Created December 1, 2009 15:11
Show Gist options
  • Save dstrelau/246347 to your computer and use it in GitHub Desktop.
Save dstrelau/246347 to your computer and use it in GitHub Desktop.
#
# Rack middleware to log both request info and server response.
#
# Usage:
# use RequestResponseLogger,
# :logfile => Rails.root.join('log','mobile.log'),
# :path => /^\/mobile\//
class RequestResponseLogger
def initialize(app, options={})
@app = app
@logfile = options[:logfile] || options['logfile'] ||
File.join(File.dirname(__FILE__),'log','request_response.log')
@path = options[:path] || options['path'] || /.*/
end
def call(env)
response = @app.call(env)
log(@logfile, response, env) if env['PATH_INFO'] =~ @path
response
end
def log(logfile, response, env)
File.open(logfile,'a') {|f|
f.puts <<-EOF
#{env['REMOTE_ADDR']} at #{Time.now}
[#{env['REQUEST_METHOD']}] #{env['SERVER_NAME']}#{env['PATH_INFO']}
Parameters: #{env['rack.request.query_hash'].inspect}
Response: #{response[0]}
#{response[2].each {|line| f.puts line}}
EOF
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment