[英]Perl not able to tail rotated log file
I am using property based filters of rsyslog to send specific logs to seperate file where those logs will be parsed using perl. 我正在使用基于属性的rsyslog过滤器将特定日志发送到单独的文件,在这些文件中将使用perl解析这些日志。
This is my rsyslog entry 这是我的rsyslog条目
$template SPLIT,"/home/shivam/hello-%$YEAR%%$MONTH%%$DAY%%$HOUR%%$MINUTE%"
:msg, contains, "hello" -?SPLIT
So rsyslog will create separate files for logs coming after every minute. 因此,rsyslog将为每分钟之后出现的日志创建单独的文件。 Files will be created like this hello-201505281139
. 文件将被创建为hello-201505281139
。
My perl script to parse these files is 我解析这些文件的Perl脚本是
use strict;
use warnings;
use POSIX qw(strftime);
my $date = strftime "%Y%m%d%H%M", localtime;
my $file = '/root/defer-'.$date;
open(my $fh,'<',$file) or die "unable to open file $!\n";
while(1) {
while(my $line = <$fh>){
print "$date\n";
print "$line";
}
sleep(2);
unless ($date == strftime "%Y%m%d%H%M", localtime) {
close($fh);
$date = strftime "%Y%m%d%H%M", localtime;
$file = '/root/defer-'. $date;
system("touch $file");
open(my $fh,'<',$file) or die "unable to open file $!\n";
}
}
In unless block i am checking that if minute has changed then i close previous file and open new file. 在除非块中,否则我正在检查分钟是否已更改,然后我关闭上一个文件并打开新文件。 The reason i am creating new file from script and not waiting for rsyslog to create file is that the frequency of logs coming is not that much. 我从脚本创建新文件而不等待rsyslog创建文件的原因是日志的出现频率不是那么高。 So i create file and just start reading on it in hope that when any new log will come i will be able to read that. 因此,我创建了文件并开始阅读它,希望当任何新日志出现时我都能阅读。
But what is happening is that i am able to create new file but not able to read anything from that file. 但是正在发生的事情是我能够创建新文件,但无法从该文件读取任何内容。
This is what i am getting as warning 这就是我得到的警告
readline() on closed filehandle $fh at test.pl line 14.
Line 14 in my code is this line while(my $line = <$fh>){
我的代码中的第14行是while(my $line = <$fh>){
I am not able to see anything wrong in my code. 我在代码中看不到任何错误。 Please suggest what is the mistake. 请提出错误所在。
You have two different $fh
lexical (my) variables, 您有两个不同的$fh
词法(我)变量,
So instead declaring new one 所以改为声明一个新的
open(my $fh,'<',$file) or die "unable to open file $!\n";
keep using previously declared one, 继续使用先前声明的
open($fh,'<',$file) or die "unable to open file $!\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.