开发者

ruby sendmail after pattern found in IO

I'm sure that I am missing something. Basicaly I want to monitor a logs IO and if a FATAL ERROR is logged to send an email with the error enclosed.

#!/usr/bin/ruby -w

require 'rubygems'

def mailer(line)

  date = `date +%D-%T`
  f = File.open("/root/error.mail", "w")
  f.puts("Subject: Fatal Error on SERVER #{date}\n\n#{line}")
  f.close
  system("sendmail guy@foo.com.com < /root/error.mail")
end

def fatal_check(file, pattern)

  f = File.open(file, "r")
  f.seek(0,IO::SEEK_END)
  while true do
    select([f])
    line = f.gets
    mailer("#{line}") if line=~pattern
    #system("./mailer.rb #{line}") if line=~pattern
  end
end

fatal_check("/root/test.log", /FATAL ERROR/)
开发者_开发技巧


How about this. You'll need a couple of gems:

gem install file-tail
gem install pony

And then your script:

require 'rubygems'
require 'pony'
require 'file/tail'

def fatal_check(file, pattern)
  File::Tail::Logfile.open(file, :backward => 0) do |log|
    log.tail do |line| 
      date = `date +%D-%T`
      Pony.mail(:to => 'you@example.com', :from => 'me@example.com', :subject => "There was a nasty error on #{date}", :body => line)
    end
  end
end

fatal_check(File.dirname(__FILE__) + "/test.log", /FATAL/)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜