diff --git a/lib/rackstash/filters.rb b/lib/rackstash/filters.rb index d484ec4..0fc87c3 100644 --- a/lib/rackstash/filters.rb +++ b/lib/rackstash/filters.rb @@ -5,6 +5,7 @@ # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE.txt file for details. +require 'rackstash/filters/clear_color' require 'rackstash/filters/skip_event' module Rackstash diff --git a/lib/rackstash/filters/clear_color.rb b/lib/rackstash/filters/clear_color.rb new file mode 100644 index 0000000..665b757 --- /dev/null +++ b/lib/rackstash/filters/clear_color.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true +# Copyright 2017 Holger Just +# +# This software may be modified and distributed under the terms +# of the MIT license. See the LICENSE.txt file for details. + +module Rackstash + module Filters + # Remove all ANSI color codes from the `"message"` field of the given event + # `Hash`. + class ClearColor + # a regular expression matching ANSI color codes + COLOR_REGEX = /\e\[[0-9;]*m/.freeze + + # Remove all ANSI color codes from the `"message"` field. The field can + # either contain a single String or {Message} or an Array of those. If + # there is no message, we return the event unchanged. + # + # @param event [Hash] an event hash + # @return [Hash] the given `event` with all ANSI color codes removed from + # messages + def call(event) + message = event[FIELD_MESSAGE] + case message + when Array + message.map! { |msg| + msg.gsub(COLOR_REGEX, EMPTY_STRING) + } + when String, Message + event[FIELD_MESSAGE] = message.gsub(COLOR_REGEX, EMPTY_STRING) + end + + event + end + end + end +end diff --git a/spec/rackstash/filters/clear_color_spec.rb b/spec/rackstash/filters/clear_color_spec.rb new file mode 100644 index 0000000..407999b --- /dev/null +++ b/spec/rackstash/filters/clear_color_spec.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true +# Copyright 2017 Holger Just +# +# This software may be modified and distributed under the terms +# of the MIT license. See the LICENSE.txt file for details. + +require 'spec_helper' + +require 'rackstash/filters/clear_color' + +describe Rackstash::Filters::ClearColor do + let(:filter) { described_class.new } + + it 'removes any ANSI color codes from the message' do + event = { 'message' => "Important\n\e[31mRED TEXT\e[0m\nOK" } + expect(filter.call(event)).to eql 'message' => "Important\nRED TEXT\nOK" + end + + it 'removes color codes from a message array' do + event = { + 'message' => ["Some \e[31mred\e[0m\nand", "some \e[32mgreen\e[0m text" ] + } + expect(filter.call(event)).to eql 'message' => [ + "Some red\nand", "some green text" + ] + end + + it 'does nothing if there is no message field' do + event = { 'foo' => 'bar' } + expect(filter.call(event)).to eql 'foo' => 'bar' + end + +end