计算 /var/log/messages 中日志消息之间的最大时间差

计算 /var/log/messages 中日志消息之间的最大时间差

我需要计算 /var/log/messages 中两个日志消息之间的时间差。我们知道日志消息以日期和时间作为前缀,因此我想要两个日志条目之间的时间差。

答案1

我选择了第一条和最后一条消息进行/var/log/messages演示,您必须对其进行修改才能获得自己的开始和结束时间

#!/bin/bash

start=$(head -n 1 /var/log/messages | awk {'print $1, $2,$3'})
finish=$(tail -n 1 /var/log/messages | awk {'print $1, $2,$3'})

start_secs=$(date -d "$start" +"%s")
finish_secs=$(date -d  "$finish" +"%s")

let diff_secs=($finish_secs - $start_secs)

let days=$diff_secs/86400
let remainder=$diff_secs%86400
let hours=$remainder/3600
let remainder=$remainder%3600
let minutes=$remainder/60
let seconds=$remainder%60
echo "Days = $days, Hours = $hours, Minutes = $minutes, Seconds = $seconds"

答案2

在 bash 中,一旦你确定了要使用的日期/时间,你可以编写

firsttime="Jun  1 02:00:13"
secondtime="Jun  1 03:00:46"
echo $(( $(date -d "$secondtime" +"%s") - $(date -d "$firsttime" +"%s") ))

这将为您提供两次之间的秒数。如果您想自动查找第一次和第二次,您必须告诉我们您在日志中究竟要查找什么。

答案3

我假设您想要找到两个连续日志消息之间的最大时间间隔。如果是这样,请参阅下面的脚本,该脚本应该可以解决问题。几年前,我编写了这个脚本来从消息文件中打印出特定的时间范围,并且它很容易自定义:

#!/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";

相关内容