Class: Lognotifier::Application

Inherits:
Object
  • Object
show all
Defined in:
lib/lognotifier/application.rb

Constant Summary collapse

CONFIG_FILE =
'/etc/lognotifier.yaml'

Instance Method Summary collapse

Constructor Details

#initializeApplication

Returns a new instance of Application.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/lognotifier/application.rb', line 7

def initialize
  # Load configuration:
  begin
    @config = YAML.load(File.read CONFIG_FILE)
  rescue => e
    puts 'Error at opening config file, error was:'
    puts e.message
    exit 1
  end

  # Initializa logger:
  @logger = Logger.new @config['logfile']

  # Main exec loop
  run
end

Instance Method Details

#runObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/lognotifier/application.rb', line 24

def run
  @logger.info 'Starting lognotifierd'

  threads = []
  @config['pagerduty'].each do |conf|

    threads << Thread.new do

      # Variables:
      filename = conf[0]
      config = conf[1]

      # Initialize pager duty:
      pagerduty = Pagerduty.new(config['servicekey'])

      # Exit if file not exists
      begin
        file = File.open(filename)
        @logger.info "Opening file #{filename} for log pattern search"
      rescue => e
        @logger.error "ERROR OPENING FILE: #{filename}"
        @logger.error "ERROR WAS: #{e.message}"
        Thread.exit
      end

      # Seek to the end of the file and watch for changes
      file.seek(0, IO::SEEK_END)
      queue = INotify::Notifier.new

      # previous to nil to record the previous line
      previous = nil

      # Watch for modified actions, read the content and alert if match
      # When alerting also send the previous line if available
      queue.watch(filename, :modify) do
        content = file.read
        config['patterns'].each do |pattern|
          next unless content.match(/#{pattern["regex"]}/)
          message = ''
          message += previous.chomp + ' | ' unless previous.nil? || previous == content
          message += content.chomp
          begin
            pagerduty.trigger("#{pattern['prefix']} #{message}")
            @logger.info("ALERT TRIGGERD - #{pattern['prefix']}: #{message}")
          rescue => e
            @logger.error("FAILED TO SEND ALERT: #{pattern['prefix']} #{message}")
            @logger.error("Error: #{e.message}")
          end
        end
        previous = content
      end
      queue.run
    end
  end
  threads.each(&:join)
end