diff --git a/lib/lograge.rb b/lib/lograge.rb index b4ca5da6..dfd70cc0 100644 --- a/lib/lograge.rb +++ b/lib/lograge.rb @@ -32,6 +32,18 @@ def self.custom_options(event) end end + # Before format allows you to change the structure of the output. + # You've to pass in something callable + # + mattr_writer :before_format + self.before_format = nil + + def self.before_format(data, payload) + result = nil + result = @@before_format.call(data, payload) if @@before_format + result || data + end + # Set conditions for events that should be ignored # # Currently supported formats are: @@ -106,6 +118,7 @@ def self.setup(app) Lograge.remove_existing_log_subscriptions Lograge::RequestLogSubscriber.attach_to :action_controller Lograge.custom_options = app.config.lograge.custom_options + Lograge.before_format = app.config.lograge.before_format Lograge.log_level = app.config.lograge.log_level || :info self.support_deprecated_config(app) # TODO: Remove with version 1.0 Lograge.formatter = app.config.lograge.formatter || Lograge::Formatters::KeyValue.new diff --git a/lib/lograge/log_subscriber.rb b/lib/lograge/log_subscriber.rb index a3558ce9..ea9655b6 100644 --- a/lib/lograge/log_subscriber.rb +++ b/lib/lograge/log_subscriber.rb @@ -7,7 +7,7 @@ module Lograge class RequestLogSubscriber < ActiveSupport::LogSubscriber def process_action(event) return if Lograge.ignore?(event) - + payload = event.payload data = extract_request(payload) @@ -16,6 +16,7 @@ def process_action(event) data.merge! location(event) data.merge! custom_options(event) + data = before_format(data, payload) formatted_message = Lograge.formatter.call(data) logger.send(Lograge.log_level, formatted_message) end @@ -67,6 +68,10 @@ def custom_options(event) Lograge.custom_options(event) || {} end + def before_format(data, payload) + Lograge.before_format(data, payload) + end + def runtimes(event) { :duration => event.duration, diff --git a/spec/lograge_logsubscriber_spec.rb b/spec/lograge_logsubscriber_spec.rb index 5582f564..cbd2d0fd 100644 --- a/spec/lograge_logsubscriber_spec.rb +++ b/spec/lograge_logsubscriber_spec.rb @@ -162,6 +162,27 @@ end end + describe "with before_format configured for lograge output" do + before do + Lograge.formatter = Lograge::Formatters::KeyValue.new + Lograge.before_format = nil + end + + it "should output correctly" do + Lograge.before_format = lambda { |data, payload| + Hash[*data.first].merge(Hash[*payload.first]) + } + subscriber.process_action(event) + log_output.string.should include("method=GET") + log_output.string.should include("status=200") + end + it "should work if the method returns nil" do + Lograge.before_format = lambda {|data, payload| nil} + subscriber.process_action(event) + log_output.string.should be_present + end + end + describe "with ignore configured" do before do # Lograge::log_format = :lograge