Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle json Encoding::UndefinedConversionError #165

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Prev Previous commit
Next Next commit
Catch all format errors and return a meaningful message
  • Loading branch information
marcoadkins committed Sep 16, 2020
commit ee1c5d8e329227cb9b06d6f311f621798cfc35ee
4 changes: 4 additions & 0 deletions lib/logstash-logger/formatter/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module Formatter
HOST = ::Socket.gethostname

class Base < ::Logger::Formatter
FAILED_TO_FORMAT_MSG = 'Failed to format log event'
attr_accessor :error_logger
include ::LogStashLogger::TaggedLogging::Formatter

Expand All @@ -19,6 +20,9 @@ def initialize(customize_event: nil, error_logger: LogStashLogger.configuration.
def call(severity, time, _progname, message)
event = build_event(message, severity, time)
format_event(event) unless event.cancelled?
rescue StandardError => e
log_error(e)
FAILED_TO_FORMAT_MSG
end

private
Expand Down
16 changes: 16 additions & 0 deletions spec/formatter/base_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,22 @@
expect(subject.call(severity, time, progname, message)).to be_nil
end
end

context "when exception is raised" do
before do
allow(subject).to receive(:error_logger).and_return(Logger.new('/dev/null'))
allow(subject).to receive(:format_event).and_throw
end

it "logs an exception" do
expect(subject).to receive(:log_error)
subject.call(severity, time, progname, message)
end

it "retruns a failed to format message" do
expect(subject.call(severity, time, progname, message)).to eq(LogStashLogger::Formatter::Base::FAILED_TO_FORMAT_MSG)
end
end
end

describe '#force_utf8_encoding' do
Expand Down