Class: Fluent::AddFilter

Inherits:
Filter
  • Object
show all
Defined in:
lib/fluent/plugin/filter_switch.rb

Instance Method Summary collapse

Constructor Details

#initializeAddFilter

Returns a new instance of AddFilter.



10
11
12
# File 'lib/fluent/plugin/filter_switch.rb', line 10

def initialize
  super
end

Instance Method Details

#configure(conf) ⇒ Object



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

def configure(conf)
  super
  # config file validations
  if !['append', 'replace'].include? action
     raise Fluent::ConfigError, "undefined action, select: 'append' or 'replace'"
  end

  # do more config validation
  ###

  # create the condition / value array
  @list = []
  conf.elements.select { |element| element.name == 'case' }.each do |element|
    element_hash = element.to_hash
    if ['condition', 'value'].all? {|s| element_hash.key? s}
      map = { 'condition' => element_hash['condition'], 'value' => element_hash['value']}
      @list.push(map)
    else
      raise Fluent::ConfigError, "use 'condtion' key for pattern matching, and use 'value' key for replacement value"
    end
  end
end

#filter(tag, time, record) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/fluent/plugin/filter_switch.rb', line 65

def filter(tag, time, record)
  pass_thru = record
  begin
    value = revalue(record)
    if action == 'append'
      record = record.merge!(category_name => value)
    else
      if record.has_key? category_name
        record[category_name] = value
      else
        raise Fluent::ConfigError, "can't find the key in record to replace its value"
      end
    end
  rescue Exception => e
    log.error e.message
    log.error e.backtrace.inspect
    log.info 'an exception occurred while filtering, returning the original record'
    return pass_thru
  end
  record
end

#revalue(record) ⇒ Object

method to remap based the conditions in the config



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/fluent/plugin/filter_switch.rb', line 38

def revalue(record)

  # create the string to be compared against conditions
  payload = ''
  if key_space == 'all'
   array = record.each{|key, value| value}
   payload = array.join(',')
  else
    keys = key_space.split(',')
    if keys.all? {|elem| record.key? elem}
        keys.each do |key|
          payload = payload + record[key]    
        end
    else
      raise Fluent::ConfigError, "one or more keys provided don't exist in the record"
    end
  end
  @list.each do |hash|
    regex_pattern = Regexp.new hash['condition']
    if regex_pattern =~ (payload)
      return hash['value']
    end
  end
  return (default_value) ? default_value : record[category_name]
end