From 9656297762bb988868146b1e93cd4c7e6625e8cf Mon Sep 17 00:00:00 2001 From: Holger Just Date: Sat, 22 Jul 2017 00:06:35 +0200 Subject: [PATCH] Remove ANSI color codes from the message in JSON encoder --- lib/rackstash/encoders/json.rb | 8 ++++++-- spec/rackstash/encoders/json_spec.rb | 5 +++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/rackstash/encoders/json.rb b/lib/rackstash/encoders/json.rb index b6442c2..33be4ed 100644 --- a/lib/rackstash/encoders/json.rb +++ b/lib/rackstash/encoders/json.rb @@ -11,7 +11,8 @@ module Rackstash module Encoders # The JSON encoder formats the log event as a single-line JSON string. The # resulting JSON string contains all data exposed by the buffer. Leading - # and trailing whitespace on the `"message"` field will be removed. + # and trailing whitespace as well as any ANSI color codes in the `"message"` + # field will be removed. # # The resulting string is in the JSON format native to Logstash. You can # thus ship your logs directly to Logstash without further processing by @@ -23,7 +24,10 @@ module Rackstash # @param event [Hash] a log event as produced by the {Flow} # @return [String] the event as a single-line JSON string def encode(event) - event[FIELD_MESSAGE] = event[FIELD_MESSAGE].strip + event[FIELD_MESSAGE] = event[FIELD_MESSAGE] + .gsub(/\e\[[0-9;]*m/, EMPTY_STRING) + .strip + ::JSON.dump(event) end end diff --git a/spec/rackstash/encoders/json_spec.rb b/spec/rackstash/encoders/json_spec.rb index 8779864..5da1a6f 100644 --- a/spec/rackstash/encoders/json_spec.rb +++ b/spec/rackstash/encoders/json_spec.rb @@ -27,5 +27,10 @@ describe Rackstash::Encoders::JSON do event = { 'message' => "\n\t \nline1\nline2\n \n\t\n" } expect(encoder.encode(event)).to eql '{"message":"line1\nline2"}' end + + it 'removes any ANSI color codes from the message' do + event = { 'message' => "Important\n\e[31mRED TEXT\e[0m\nOK" } + expect(encoder.encode(event)).to eql '{"message":"Important\nRED TEXT\nOK"}' + end end end