Skip to content

Instantly share code, notes, and snippets.

@aereal
Last active December 12, 2015 09:19
Show Gist options
  • Save aereal/4750438 to your computer and use it in GitHub Desktop.
Save aereal/4750438 to your computer and use it in GitHub Desktop.
Rails example to log session as LTSV (Labeled Tab-separated Values)
class Application < Rails::Application
config.middleware.use LtsvRequestLogger
end
class LtsvRequestLogger
def initialize(env)
@app = app
end
def call(env)
@app.call(env).tap do |(status, headers, body)|
log_session(ActionDispatch::Request.new(env), ActionDispatch::Response.new(status, headers, body))
end
end
def log_session(request, response)
stash = {
method: request.request_method,
status: response.status,
uri: request.filtered_path,
host: request.ip,
ua: request.user_agent,
}
stash[:referer] = request.referer unless request.referer.blank?
stash[:runtime] = response['X-Runtime'] unless response['X-Runtime'].blank?
Rails.logger.info(stash.each_entry.map {|(key, value)| "#{key}:#{value}" }.join("\t") + "\t")
end
end
@aereal
Copy link
Author

aereal commented Feb 10, 2013

I've swapped Rails::Rack::Logger for this middleware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment