如何在perl脚本中不断更新日志文件并匹配特定模式

问题描述 投票:0回答:2

我想继续阅读更新日志文件。如果我得到特定模式,那么我应该能够发送一封我能够做的邮件。

use strict;
use warnings;
my $line;
my $to = '[email protected]';
my $from = '[email protected]';
my $subject = 'Connection Pool Issue';
my $message = 'There is connection pool issue. Please check Logs for more details';

open my $fh, '<', 'error.txt';
my @file = <$fh>;
close $fh;

foreach my $line (@file) {


 if ($line =~ /The connection is closed./) 

 { 

    open(MAIL, "|/usr/sbin/sendmail -t");
    print MAIL "To: $to\n";
    print MAIL "From: $from\n";
    print MAIL "Subject: $subject\n\n";
    # Email Body
    print MAIL $message;

    close(MAIL);
    print "Email Sent Successfully\n";

    last;
  }
}

我不想从文件处理程序0读取文件,这意味着从起始位置。

我希望从当前文件处理程序位置读取一个文件。它不应该包括已经读取的行。

请建议。谢谢

perl file-handling
2个回答
1
投票

使用File::Tail

use File::Tail qw( );

my $tail = File::Tail->new( name => $qfn );
while (defined( my $line = $tail->read() )) {
   if ($line =~ /The connection is closed\./) {
      ...
   }
}

如果你需要前面的行,

use File::Tail qw( );

my $tail = File::Tail->new( name => $qfn );
my @buf;
while (defined( my $line = $tail->read() )) {
   push @buf, $line;
   if ($line =~ /The connection is closed\./) {
      ...
      @buf = ();
   }
}

0
投票

我用2种不同的方法解决了这个问题。

没有模块你可以做类似的事情:

-Check if line count file exists and read into variable
-loop through file line by line, increment counter
-if $loop_line_count < $line_count_previous_run : skip
-if $total_line_count < $line_count_previous_run : reset file count to 0
-write total_line_count to file

使用File :: Tail

my $file=File::Tail->new( name=>"$log_file",internal=>10, maxinterval=>30, adjustafter=>5);

while (defined(my $line=$file->read)) {
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.