class Fluent::Plugin::CsvFormatter

Public Instance Methods

configure(conf) click to toggle source
Calls superclass method Fluent::Plugin::Base#configure
# File lib/fluent/plugin/formatter_csv.rb, line 38
def configure(conf)
  super

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

  if @fields.any? { |f| record_accessor_nested?(f) }
    @accessors = @fields.map { |f| record_accessor_create(f) }
    mformat = method(:format_with_nested_fields)
    singleton_class.module_eval do
      define_method(:format, mformat)
    end
  end

  @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
format(tag, time, record) click to toggle source
# File lib/fluent/plugin/formatter_csv.rb, line 58
def format(tag, time, record)
  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
format_with_nested_fields(tag, time, record) click to toggle source
# File lib/fluent/plugin/formatter_csv.rb, line 67
def format_with_nested_fields(tag, time, record)
  csv = (@cache[Thread.current] ||= CSV.new("".force_encoding(Encoding::ASCII_8BIT), **@generate_opts))
  values = @accessors.map { |a| a.call(record) }
  line = (csv << values).string.dup
  # Need manual cleanup because CSV writer doesn't provide such method.
  csv.rewind
  csv.truncate(0)
  line
end