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

formatter_csv: Improve the performance. 2x faster #2529

Merged
merged 1 commit into from
Jul 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions lib/fluent/plugin/formatter_csv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,22 @@ class CsvFormatter < Formatter

def configure(conf)
super

@fields = fields.select{|f| !f.empty? }
raise ConfigError, "empty value is specified in fields parameter" if @fields.empty?

@generate_opts = {col_sep: @delimiter, force_quotes: @force_quotes}
@generate_opts = {col_sep: @delimiter, force_quotes: @force_quotes, headers: @fields,
row_sep: @add_newline ? :auto : "".force_encoding(Encoding::ASCII_8BIT)}
# Cache CSV object per thread to avoid internal state sharing
@cache = {}
end

def format(tag, time, record)
row = @fields.map do |key|
record[key]
end
line = CSV.generate_line(row, @generate_opts)
line.chomp! unless @add_newline
csv = (@cache[Thread.current] ||= CSV.new("".force_encoding(Encoding::ASCII_8BIT), @generate_opts))
line = (csv << record).string.dup
# Need manual cleanup because CSV writer doesn't provide such method.
csv.rewind
csv.truncate(0)
line
end
end
Expand Down
16 changes: 16 additions & 0 deletions test/plugin/test_formatter_csv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,20 @@ def test_config_params_with_fields(data)
d = create_driver('fields' => data)
assert_equal %w(one two three), d.instance.fields
end

def test_format_with_multiple_records
d = create_driver("fields" => "message,message2")
r = {'message' => 'hello', 'message2' => 'fluentd'}

formatted = d.instance.format(tag, @time, r)
assert_equal("\"hello\",\"fluentd\"\n", formatted)

r = {'message' => 'hey', 'message2' => 'ho'}
formatted = d.instance.format(tag, @time, r)
assert_equal("\"hey\",\"ho\"\n", formatted)

r = {'message' => 'longer message', 'message2' => 'longer longer message'}
formatted = d.instance.format(tag, @time, r)
assert_equal("\"longer message\",\"longer longer message\"\n", formatted)
end
end