Perl script to grep through all your logs for recent errors

Home

Toolkit:

My OraFAQ Blog

Contact me

Perl script to grep through multiple alert logs for errors. You can specify how many days in the past you'd like to search back through the logs for errors. If any errors are found, they are recorded in an output file.

Sample Output

# LOG_GREPPER.PL
# Natalka Roshak, 2001
#
# Perl script to grep through your logfiles for ORA- errors
# On UNIX, preface it with #!/bin/perl or some such
# Replace the outputfile, and the arguments to grep_log, below with your own files 
# Use mapped drives to access logfiles on different machines (NT), or use NFS 
# (Unix), or add some scp in to copy all your logs to the same machine (Unix)

$outputfile="D:\\tree\\log_grep.out";
open(OUT, "> -");
open(FOUT, "> $outputfile");

print OUT "Enter number of days back: ";
open(IN, "< -");
$ln=;
close(IN);

# get number of seconds back

$secs=$ln*86400;
print OUT "$secs\n";

$now_string=localtime(time-$secs);
print OUT "$now_string\n";

#get string to grep for

($first,$second,$third,$rest)=split(/ /,$now_string,4);
$now_string= "$first" . " " . "$second" . " " . "$third" ;
print OUT "$now_string\n";


print OUT "$now_string\n";

$happystr="-------------------------------------------------------------------";

print FOUT localtime(time) . "\n\n";

grep_log("e:\\oracle\\my_log_1.log");
grep_log("f:\\oracle\\my_log_2.log");
grep_log("g:\\oracle\\my_log_3.log");

sub grep_log {

$logfile=$_[0];
open(LOG, "< $logfile") or die "Can't open log $logfile : $!"; 
print OUT "Opened log...\n";
print OUT "\n$happystr\n$logfile\n";
print FOUT "$happystr\n\nLogfile: $logfile\n\n";
my $isittrue='';
my $lno=0;
my $tag=0;
my $lastline='';
my $prevline='';
while (defined (my $line=))  {
	chomp $line;
	if (length($isittrue)==0) {
		if ($line=~/$now_string/) {
			$isittrue="Oo";
			print OUT "I hit a match on line $lno";
		}
	}
	elsif (length($isittrue) != 0) {
		if ($line=~/ORA-/ ) {
			if ($tag<=0) {
				print FOUT "-----\n";
				print FOUT "$lno\t$prevline\n";
				print FOUT "$lno\t$lastline\n";
			}		
			$tag=3;
			print FOUT "$lno\t$line\n"; 
			if ($line=~/at line 1/) {
				$tag=0;
			}
		} 
		elsif ($tag>0) {
			$tag=$tag-1;
			print FOUT "$lno\t$line\n"; 
		}
	}
	$lno=$lno+1;
	$prevline=$lastline;
	$lastline=$line;
}
close(LOG);
print FOUT "\n$happystr";
}
print OUT "$happystr\n";
print FOUT "$happystr\n";

close(OUT);
close(FOUT) or die "Output file not closed: $!";

exec("c:\\winnt\\notepad $outputfile");
end;


Note: Proofread any scripts before using. Always try scripts on a test instance first. I'm not responsible for any damage, even if you somehow manage to make my scripts corrupt every last byte of your data, set your server on fire and serve you personally with an eviction notice from your landlord!
All scripts and tips © Natalka Roshak 2001-2005.
Enjoy the FREE tips folks...