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

How to read continuously updating log file & match particular pattern in perl script

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

use strict;
use warnings;
my $line;
my $to = 'abc@abc.com';
my $from = 'xyz@abc.com';
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 中读取文件,这意味着从起始位置开始。

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

求推荐。 谢谢

使用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 = ();
   }
}

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

在没有模块的情况下,您可以执行以下操作:

-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)) {
    ...
}