2011年4月11日 星期一

scan log file in perl

rewrite an old script to run on linux and scan for jboss log
used for hourly scan this hours' log
把幾年前用的script又搬出來改寫,好符合現在的環境,並且可以指定任意log檔
每小時59分parse一次,會去檢查這一小時的log
但是沒很漂亮,可能不同環境還是要修改
##################################################################

#!/usr/bin/perl -w

use strict;
use diagnostics;

### Variables defined here ###
my $domain = ""; # used in mail sender
chomp(my $host = "" || "localhost"); # hostname
my $DIR = "/jboss/logs"; # log directory
my $l_log = "server.log"; # log name
my $SENDMAIL = '/usr/lib/sendmail';
### regular express here ###
my $keyword = '( ERROR )';
### use , to seperate and put \ before @  ###
my $Admins = "aaa\@abc.com";

### Date & time ###
my ($sec,$min,$hour,$mday,$mon,$year,$wday) = localtime;
my $today = sprintf("%04d", $year+1900) . "-" . sprintf("%02d", $mon+1) . "-" . sprintf("%02d", $mday); # get day

### main logistic here ###
### this line because the log name like system.log.2011-04-11 ###
my $filename = $DIR . "/" . $l_log . "." . $today;
my @l_log = process_log($filename, $hour, $keyword);
if ( scalar @l_log > 0 ) {
&write_mail();
}
exit; # jump out...

### functions here ###
sub process_log {
my $target_log  = shift;
my $search_time = sprintf("%02d", shift);
my $search_data = shift;
open (MY_LOGS, "$filename") or die "Can't find $filename: $!";
while () {
      chomp; # no newline...
      s/#.*//; # no comments...
      s/^\s+//; # no leading whitespace...
      s/\s+$//; # no trailing whitespace...
      next unless length; # anything to process?
      next unless /\s$search_time:"/; # only this hour
      next unless /\s$search_data\s/;
      push(@_,$_);
      }
return @_;
}

sub write_mail {
open (MAIL, "|$SENDMAIL -t") || die ("$0: Can't open $SENDMAIL: $!\n");
print MAIL "Reply-to: root\@$host.$domain\n";
print MAIL "From: \"$host Log\" \\n";
print MAIL "To: $Admins\n";
print MAIL "Subject: $host Jboss Error Log Report at ", scalar localtime, "\n";
print MAIL " report from " . $host . ":\n";
print MAIL "\n$filename -\n";
foreach (@l_log) {print MAIL "$_\n"};
close (MAIL);
}

沒有留言:

最常被訪