Skip to content

Commit

Permalink
formatter_ltsv: suppress delimiters in output
Browse files Browse the repository at this point in the history
Replace tabs with spaces before writing them to the output, to prevent
creating malformed LTSV files.

Also add test cases to verify this behaviour.

Signed-off-by: Mike Playle <mike@mythik.co.uk>
  • Loading branch information
MikePlayle committed Dec 8, 2020
1 parent 9110685 commit e7fd4c1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/fluent/plugin/formatter_ltsv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,15 @@ class LabeledTSVFormatter < Formatter

config_param :delimiter, :string, default: "\t".freeze
config_param :label_delimiter, :string, default: ":".freeze
config_param :replacement, :string, default: " ".freeze
config_param :add_newline, :bool, default: true

# TODO: escaping for \t in values
def format(tag, time, record)
formatted = ""
record.each do |label, value|
formatted << @delimiter if formatted.length.nonzero?
formatted << "#{label}#{@label_delimiter}#{value}"
formatted << "#{label}#{@label_delimiter}#{value.to_s.gsub(@delimiter, @replacement)}"
end
formatted << @newline if @add_newline
formatted
Expand Down
30 changes: 30 additions & 0 deletions test/test_formatter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,36 @@ def test_format_with_customized_delimiters

assert_equal("message=awesome,greeting=hello#{@newline}", formatted)
end

def record_with_tab
{'message' => "awe\tsome", 'greeting' => "hello\t"}
end

def test_format_suppresses_tab
@formatter.configure({})
formatted = @formatter.format(tag, @time, record_with_tab)

assert_equal("message:awe some\tgreeting:hello \n", formatted)
end

def test_format_suppresses_tab_custom_replacement
@formatter.configure(
'replacement' => 'X',
)
formatted = @formatter.format(tag, @time, record_with_tab)

assert_equal("message:aweXsome\tgreeting:helloX\n", formatted)
end

def test_format_suppresses_custom_delimiter
@formatter.configure(
'delimiter' => 'w',
'label_delimiter' => '=',
)
formatted = @formatter.format(tag, @time, record)

assert_equal("message=a esomewgreeting=hello\n", formatted)
end
end

class CsvFormatterTest < ::Test::Unit::TestCase
Expand Down

0 comments on commit e7fd4c1

Please sign in to comment.