1
0
mirror of https://github.com/meineerde/rackstash.git synced 2025-12-19 15:01:12 +00:00

Remove ANSI color codes from the message in JSON encoder

This commit is contained in:
Holger Just 2017-07-22 00:06:35 +02:00
parent da97e9d54e
commit 9656297762
2 changed files with 11 additions and 2 deletions

View File

@ -11,7 +11,8 @@ module Rackstash
module Encoders module Encoders
# The JSON encoder formats the log event as a single-line JSON string. The # 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 # 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 # The resulting string is in the JSON format native to Logstash. You can
# thus ship your logs directly to Logstash without further processing by # 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} # @param event [Hash] a log event as produced by the {Flow}
# @return [String] the event as a single-line JSON string # @return [String] the event as a single-line JSON string
def encode(event) 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) ::JSON.dump(event)
end end
end end

View File

@ -27,5 +27,10 @@ describe Rackstash::Encoders::JSON do
event = { 'message' => "\n\t \nline1\nline2\n \n\t\n" } event = { 'message' => "\n\t \nline1\nline2\n \n\t\n" }
expect(encoder.encode(event)).to eql '{"message":"line1\nline2"}' expect(encoder.encode(event)).to eql '{"message":"line1\nline2"}'
end 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
end end