Skip to content

Instantly share code, notes, and snippets.

@openfirmware
Created December 20, 2010 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save openfirmware/748778 to your computer and use it in GitHub Desktop.
Save openfirmware/748778 to your computer and use it in GitHub Desktop.
A really quick and dirty script to parse log files, look for errors, and send a report to multiple email addresses
#!/usr/bin/env ruby
require 'date'
require 'net/smtp'
# Who to send the report to
RECIPIENTS = %w( me@example.com )
# Who the message will be sent as
FROM_ADDRESS = "root@example.com"
# The log files to parse and what to look for
# Note: formats are regular expressions
LOG_FILES = [
{ :path => "/var/log/rsnapshot",
:format => "[%d/%b/%Y:%H:%M:%S]",
:error_format => "ERROR"
},
{ :path => "/var/log/mail.err",
:format => "%b %d %H:%M:%S",
:error_format => "(fatal|panic|error)"
}
]
since_date = DateTime.now - 1
gmt_offset = Rational(Time.now.gmt_offset / 3600, 24)
errors_detected = false
LOG_FILES.each do |log_file|
messages = []
File.open(log_file[:path], 'r') do |file|
begin
date = DateTime.strptime(line, log_file[:format]).newof(gmt_offset) - gmt_offset
if date > since_date
messages << line
errors_detected = true if line.match(/#{log_file[:error_format]}/)
end
rescue ArgumentError
end
end
log_file[:messages] = messages
end
RECIPIENTS.each do |recipient|
subject = "Server Status " + errors_detected ? "ERROR", "OK"
body = ""
LOG_FILES.each do |log_file|
body += "<h2>Log: #{log_file[:path]}</h2>\n"
body += "<ul>\n"
for message in log_file[:messages] do
style = message.match(/#{log_file[:error_format]}/) ? " style='color: red;'" : ""
body += "<li#{style}>#{message}</li>\n"
end
body += "</ul>\n"
end
msg = <<END_OF_MESSAGE
From: Server Status <#{FROM_ADDRESS}>
To: <#{recipient}>
MIME-Version: 1.0
Content-type: text/html
Subject: #{subject}
#{body}
END_OF_MESSAGE
Net::SMTP.start('localhost') do |smtp|
smtp.send_message msg, FROM_ADDRESS, recipient
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment