意図した順でログが出ているかを確認する perlスクリプト checkOrder.pl を作成した。
使い方は、スクリプト冒頭の以下の箇所を順番を確認したいもの(正規表現)に書き換えてから、
my @logs = ("test log message1", "test log message2", "test log message3");
perl checkOrder.pl 解析対象のログファイル
として実行する。
上記は、ログファイル内にて、test log message1 -> test log message2 -> test log message3 という行が順番で出力されているかどうか確認する例である。
なお、チェック対象以外のログについては気にしない。順番チェック対象のログ(行)が順番で出てきているのかどうか(だけ)を確認するものである。
全て順番通りであれば、
The order is OK.
と出力され、一か所でも順番通りでないところがあれば、例えば以下のように、順番が意図通りでない箇所を出力して終了する。
test log message2 (at 15 lines) is not in the order...
checkOrder.pl
use strict; use warnings; #------------------------------------------ # User customize. Specify messages by correct order (as regex). # The example below means this script checks if log messages appears in the following order. # (1) "test log message1" # (2) "test log message2" # (3) "test log message3" #------------------------------------------ my @logs = ("test log message1", "test log message2", "test log message3"); # Check the args. my $inFile = $ARGV[0]; if (! -f $inFile) { die "There is not $inFile file..."; } open(my $inFh, "< $inFile") or die("Error :$!"); my $currentLogNum = -1; my $prevLogNum = -1; my $found = 0; my $lineNum = 0; foreach my $line (<$inFh>) { $lineNum++; my $logNum = 0; foreach my $log (@logs) { # Check if the line has one of the logs. if ($line =~ /$log/) { # $line has $log (as a regex). $found = 1; $prevLogNum = $currentLogNum; $currentLogNum = $logNum; # Check if the order is correct. if ($currentLogNum != -1 and $prevLogNum != -1) { unless (isCorrectOrder($prevLogNum, $currentLogNum)) { print("$line (at $lineNum lines) is not in the order..."); exit; } } last; } $logNum++; } } close($inFh); if ($found) { print("The order is OK."); } else { print("There are not target logs..."); } sub isCorrectOrder { my ($prevLogNum, $currentLogNum) = @_; if (($currentLogNum == $prevLogNum + 1) or ($prevLogNum == $#logs and $currentLogNum == 0)) { return 1; } return 0; }
マルチスレッドのプログラムにて、各スレッドが意図した順で動いているのかを確認する際、各スレッドのログが意図した順で出ているのかでチェックすると有効なことがあり、このスクリプトを作成した。ログファイルが短ければ目視で確認できるが、長大な場合は目視で確認できないので、そういう時に使えると思う。