Class: Fluent::Plugin::SprintfFormatter

Inherits:
Formatter
  • Object
show all
Defined in:
lib/fluent/plugin/formatter_sprintf.rb

Instance Method Summary collapse

Constructor Details

#initializeSprintfFormatter

Returns a new instance of SprintfFormatter.



12
13
14
# File 'lib/fluent/plugin/formatter_sprintf.rb', line 12

def initialize
  super
end

Instance Method Details

#configure(conf) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/fluent/plugin/formatter_sprintf.rb', line 16

def configure(conf)
  super
  @time_format = @time_format || '%Y-%m-%d %H:%M:%S'
  r = /\$\{([^}]+)\}/
  @keys = @sprintf_format.scan(r).map{ |key| key.first }
  @sprintf_format = @sprintf_format.gsub(/\$\{([^}]+)\}/, '%s')
  if @sprintf_blank_record_format
    @sprintf_blank_record_keys = @sprintf_blank_record_format.scan(r).map{ |key| key.first }
    @sprintf_blank_record_format = @sprintf_blank_record_format.gsub(/\$\{([^}]+)\}/, '%s')
  end

  begin
    @sprintf_format % @keys
  rescue ArgumentError => e
    raise Fluent::ConfigError, "formatter_sprintf: @sprintf_format is can't include '%'"
  end
end

#format(tag, time, record) ⇒ Object



34
35
36
37
38
39
# File 'lib/fluent/plugin/formatter_sprintf.rb', line 34

def format(tag, time, record)
  if record.empty? && @sprintf_blank_record_format
    return @sprintf_blank_record_format % get_values(@sprintf_blank_record_keys, tag, time, record)
  end
  @sprintf_format % get_values(@keys, tag, time, record)
end

#get_value(key, tag, time, record) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/fluent/plugin/formatter_sprintf.rb', line 47

def get_value(key, tag, time, record)
  if key == 'tag'
    tag
  elsif key == 'time'
    Time.at(time).strftime(@time_format)
  else
    return @sprintf_blank_string if record[key].nil?
    if record[key].respond_to?(:empty?) && record[key].empty?
      return @sprintf_blank_string
    end
    if record[key].class == String && record[key].strip.empty?
      return @sprintf_blank_string
    end
    record[key]
  end
end

#get_values(keys, tag, time, record) ⇒ Object



41
42
43
44
45
# File 'lib/fluent/plugin/formatter_sprintf.rb', line 41

def get_values(keys, tag, time, record)
  keys.map{ |key|
    get_value(key, tag, time, record)
  }
end