Skip to content

Instantly share code, notes, and snippets.

@mperrando
Last active August 29, 2015 14:23
Show Gist options
  • Save mperrando/2a0bf3e25dfa871a305a to your computer and use it in GitHub Desktop.
Save mperrando/2a0bf3e25dfa871a305a to your computer and use it in GitHub Desktop.
require 'rack/body_proxy'
class Lograge2
def initialize(app)
@app = app
end
def call(env)
Thread.current['lograge.data'] = {}
status, header, body = @app.call(env)
body = Rack::BodyProxy.new(body) { log(env, status) }
[status, header, body]
end
private
def log(env, status)
data = Thread.current['lograge.data'] || {}
data[:status] ||= status.to_i
data[:path] ||= env['REQUEST_PATH']
data[:method] ||= env['REQUEST_METHOD']
# here we should check if this log should be ignored
# this should be done in a callback
data[:user_agent] ||= env['HTTP_USER_AGENT']
formatted_message = formatter.call(data)
logger.send(log_level, formatted_message)
end
def formatter
lograge_config.formatter || Lograge::Formatters::KeyValue.new
end
def log_level
lograge_config.log_level || :info
end
def lograge_config
# must do this because Lograge is not setup
Rails.application.config.lograge
end
def logger
lograge_config.logger.presence || Rails.logger
end
class RequestLogSubscriber < Lograge::RequestLogSubscriber
def process_action(event)
return if Lograge.ignore?(event)
payload = event.payload
data = extract_request(payload)
extract_status(data, payload)
runtimes(data, event)
location(data)
custom_options(data, event)
Thread.current['lograge.data'] = before_format(data, payload)
end
def custom_options(data, event)
Lograge.custom_options = lograge_config.custom_options
options = Lograge.custom_options(event)
data.merge! options if options
end
def lograge_config
# must do this because Lograge is not setup
Rails.application.config.lograge
end
end
RequestLogSubscriber.attach_to :action_controller
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment