Class: LogStash::Filters::Math

Inherits:
Base
  • Object
show all
Defined in:
lib/logstash/filters/math.rb

Overview

Works with float and integer values

Instance Method Summary collapse

Instance Method Details

#filter(event) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/logstash/filters/math.rb', line 43

def filter(event)
  return unless filter?(event)
  for calculation in calculate do
    # Check that all the fields exist and are numeric
    next unless event.include?(calculation[1])
    next unless event.include?(calculation[2])
    next unless event.get(calculation[1]) == 0 or event.get(calculation[1]).is_a? Float or event.get(calculation[1]).is_a? Integer
    next unless event.get(calculation[2]) == 0 or event.get(calculation[2]).is_a? Float or event.get(calculation[2]).is_a? Integer
    case calculation[0]
    when "add"
      event.set( calculation[3], event.get(calculation[1]) + event.get(calculation[2]) )
    when "sub"
      event.set(calculation[3], event.get(calculation[1]) - event.get(calculation[2]) )
    when "div"
      # Avoid division by zero
      next if event.get( calculation[2] ) == 0
      event.set( calculation[3], event.get( calculation[1]).to_f / event.get(calculation[2]) )
    when "mpx"
      event.set( calculation[3], event.get( calculation[1]) * event.get( calculation[2] ) )
    end # case calculation[0]
  end # for each calculate
  filter_matched(event)
end

#registerObject



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/logstash/filters/math.rb', line 29

def register
  # Do some sanity checks that calculate is actually an array-of-arrays, and that each calculation (sub-array)
  # is exactly 4 fields and the first field is a valid calculation opperator name.
  for calculation in calculate do
    if calculation.length % 4 != 0
      abort("Each calculation must have 4 elements, this one had " + calculation.length + " " + calculation.to_s )
    end # end calculaction.length is 4
    if ! calculation[0].match('^(add|sub|div|mpx)$' )
      abort("First element of a calculation must be add|sub|div|mpx, but is: " + calculation[0] )
    end # if calculation[0] valid
  end # for each calculate
end