如何在Perl脚本中读取持续更新的日志文件并匹配特定模式

时间:2019-04-23 17:34:01

标签: perl file-handling

我想读取不断更新的日志文件。如果我有特定的模式,那么我应该能够发送能够执行的邮件。

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中读取文件,这意味着从起始位置开始。

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

请提出建议。 谢谢

2 个答案:

答案 0 :(得分: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 = ();
   }
}

答案 1 :(得分:0)

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

没有模块,您可以执行以下操作:

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