![](/img/trans.png)
[英]Using Perl how to read in a file and parse through logs to find error logs and output to a log.txt file
[英]Perl Program to parse through error log file, extract error message and output to new file
我需要編寫一個perl程序,在其中通過錯誤日志進行解析並將錯誤消息輸出到新文件。 我在設置正則表達式時遇到了問題。 在錯誤日志中,錯誤代碼以單詞“ ERROR”開頭,每個錯誤消息的末尾均以“。”(句號和空格)結尾。 我想查找所有錯誤,對它們進行計數,並將每個錯誤消息的整個錯誤消息輸出到一個新文件。
我嘗試了這個,但是遇到了問題:
open(FH,"<$filetoparse");
$outputfile='./errorlog.txt';
open(OUTPUT,">$outputfile");
$errorstart='ERROR';
$errorend=". ";
while(<FH>)
{
if (FH=~ /^\s*$errorstart/../$errorend/)
{
print OUTPUT "success";
}
else
{
print OUTPUT "failed";
}
}
}
$ errorstart和$ errorend是我在網上看到的,並且不確定這是否是正確的編碼方式。
我也知道打印“成功”或“失敗”不是我要查找的內容,我補充說以幫助確認代碼有效,我還沒有嘗試過對錯誤消息進行計數。
在這段代碼之前,我有一條打印語句,詢問用戶要解析的.txt文件的位置地址。 我確認該代碼字的特定部分正確。 謝謝你的幫助! 讓我知道是否需要更多信息!
這是我將使用的數據示例:
樣本數據
-----開始加載-----
成功:文件已正確加載。
成功:文件已正確加載。
成功:文件已正確加載。
成功:文件已正確加載。
成功:文件已正確加載。
成功:文件已正確加載。
錯誤:文件由於未知原因而無法加載。
成功:文件已正確加載。
成功:文件已正確加載。
錯誤:文件無法加載,這只是一個跨度日志文件的示例
多行。
成功:文件已正確加載。
------結束加載-------
盡管日志不一定需要跨越多行,但整個日志中會有一些數據與上面的類似。 記錄的每條消息均以SUCCESS或ERROR開頭,並且在遇到“。”(空白時間間隔空白)時完成該消息。 我想解析的日志有50,000個條目,因此不用多說,我想編寫代碼,因此它還將識別多行錯誤消息,並將整個多行消息輸出到輸出文件。
更新
我已經編寫了代碼,但是由於某種原因它無法正常工作。 我認為這與定界符有關,但我不知道這是什么。 我正在使用的文件包含由“空白時間段換行符”分隔的消息。 你能看到我在做什么錯嗎?
{
local $/ = " .\n";
if ($outputtype == 1)
{
$outputfile="errorlog.txt";
open(OUTPUT,">>$outputfile");
$errorcount=0;
$errortarget="ERROR";
print OUTPUT "-----------Error Log-----------\n";
{
while(<FH>)
{
if ($_ =~ m/^$errortarget/)
{
print OUTPUT "$_\n";
print OUTPUT "next code is: \n";
$errorcount++;
}
}
print OUTPUT "\nError Count : $errorcount\n";
}
}
}
開始時,您的代碼存在一些問題。
use strict;
並use warnings;
。 open
錯誤少得多。 open ( my $fh, "<", $filename ) or die $!;
open
實際工作。 FH =~
不執行您認為的操作。 假設您有如下錯誤數據:
ERROR: something is broken.
WARNING: something might be broken.
INFO: not broken.
ERROR: still broken.
這段代碼可以解決問題:
use strict;
use warnings;
my $filetoparse = "myfile.txt";
my $outputfile = "errorlog.txt";
open( my $input, "<", $filetoparse ) or die $!;
open( my $output, ">", $outputfile ) or die $!;
my $count_of_errors = 0;
#set record delimiter
local $/ = " . \n";
while ( my $lines = <$input> ) {
$lines =~ s/^-----\w+ LOAD-----\n//g; #discard any 'being/end load' lines.
if ( $lines =~ m/^ERROR/ ) {
$count_of_errors++;
print {$output} $lines;
}
}
close ( $input );
close ( $output );
print "$count_of_errors errors found\n";
如果您有多行錯誤消息,那么您將需要一種稍微不同的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.