2016-04-07 14 views
0

我實際上是監視一個目錄以創建新文件(.log文件)這些文件是由某些工具和工具生成的,創建相同的文件,在此期間文件將爲空。我該如何等待,直到有東西寫入我的Perl腳本中的日誌文件

,我怎麼可以等到的東西被寫入日誌和原因是基於日誌條目,我將調用不同的腳本!

use strict; 
use warnings; 
use File::Monitor; 
use File::Basename; 
my $script1 = "~/Desktop/parser1.pl"; 
my $scrip2t = "~/Desktop/parser2.pl"; 
my $dir = "~/Desktop/tool/logs"; 
sub textfile_notifier { 
my ($watch_name, $event, $change) = @_; 

my @new_file_paths = $change->files_created; #The change object has a property called files_created, 
              #which contains the names of any new files 
for my $path (@new_file_paths) { 
    my ($base, $fname, $ext) = fileparse($path, '.log'); # $ext is "" if the '.log' extension is 
                 # not found, otherwise it's '.log'. 
    if ($ext eq '.log') { 
     print "$path was created\n"; 
     if(-z $path){ 
     # i need to wait until something is written to log 
     }else{ 
     my @arrr = `head -30 $path`; 
     foreach(@arr){ 
     if(/Tool1/){ 
      system("/usr/bin/perl $script1 $path \&"); 
     }elsif(/Tool1/){ 
     system("/usr/bin/perl $script2 $path \&"); 
     } 
    } 
} 
} 
my $monitor = File::Monitor->new(); 
$monitor->watch({ 
name  => $dir, 
recurse  => 1, 
callback => {files_created => \&textfile_notifier}, #event => handler 
}); 
$monitor->scan; 

while(1){ 
    $monitor->scan; 
} 

基本上我從grepping的一些重要信息日誌。

+0

你看了一些關於輪詢的文件句柄? – red0ct

+0

@ red0ct不!這些信息的鏈接將有所幫助 – Shantesh

+1

可以[File :: Monitor](http://search.cpan.org/~andya/File-Monitor-1.00/lib/File/Monitor.pm)是一個合理的選擇嗎? – eballes

回答

0

您正在監視日誌文件的創建。也許你可以在回調子裏面使用一個睡眠函數來等待日誌文件被寫入。您也可以監視文件更改,因爲可以擴展某些日誌文件。

3

對於你的問題的這種提法,這樣的事情可能會幫助您:

use File::Tail; 
# for log file $logname 
my @logdata; 
my $file = File::Tail->new(name => $logname, maxinterval => 1); 
while (defined(my $newline = $file->read)) { 
    push @logdata, $newline; 
    # the decision to launch the script according to data in @logdata 
} 

更多here

相關問題