Calculate highest time difference between log message in /var/log/messages
772
I need to calculate time difference between two log messages of /var/log/messages. As we know log messages prefixed by date & time , i want time difference between two log entries.
Which will give you number of seconds between those two times. If you want to automate finding firsttime and secondtime, you're going to have to tell us what exactly you're looking for in the log.
I assume you want to find the largest time gap between two consecutive log messages. If so, see below for a script that should do the trick. I wrote this script a couple of years ago to print out a particular time range from the messages file, and it was pretty easy to customize:
#!/usr/bin/perl -W
use strict;
use Time::Local;
my %MONTHS = ( "Jan" => 0, "Feb" => 1, "Mar" => 2, "Apr" => 3, "May" => 4, "Jun" => 5,
"Jul" => 6, "Aug" => 7, "Sep" => 8, "Oct" => 9, "Nov" => 10, "Dec" => 11 );
# Messages file doesn't include the year, so we need to assume that
# all messages are less than a year old and make some guesses
my $currenttime = time();
my $currentyear = (localtime($currenttime))[5];
my $currentmonth = (localtime($currenttime))[4];
my $largestgap;
my $largestgapbefore;
my $largestgapafter;
my $lasttime;
my $lastmsg;
open(FILE, "</var/log/messages") || die "Unable to open messages file: $!\n";
while(<FILE>) {
chomp;
/^(...) (..) (..):(..):(..)/;
my $year = $currentyear;
if($MONTHS{$1} > $currentmonth) {$year -= 1; }
my $time = timelocal($5, $4, $3, $2, $MONTHS{$1}, $year);
if(defined($lasttime)) {
my $gap = $time - $lasttime;
if(!defined($largestgap) || $gap > $largestgap) {
$largestgap = $gap;
$largestgapbefore = $lastmsg;
$largestgapafter = $_;
}
}
$lasttime = $time;
$lastmsg = $_;
}
close(FILE);
if(!defined($lasttime)) {
print "No entries in log file.\n";
exit;
}
print "Largest gap was: " . $largestgap . " seconds.\n";
print "Entry before the gap: " . $largestgapbefore . "\n";
print " Entry after the gap: " . $largestgapafter . "\n";
In bash, once you figure out what date/times you want to use you can write
Which will give you number of seconds between those two times. If you want to automate finding firsttime and secondtime, you're going to have to tell us what exactly you're looking for in the log.
I assume you want to find the largest time gap between two consecutive log messages. If so, see below for a script that should do the trick. I wrote this script a couple of years ago to print out a particular time range from the messages file, and it was pretty easy to customize:
I've chosen the first and last messages in
/var/log/messages
to demonstrate, you'll have to modify it to get your own start and end times