Search code examples
regexperlfilewaitmonitor

How can i wait until something is written to log file in my perl script


I am actually Monitoring a directory for creation of new files(.log files) these files are generated by some tool and tool writes log entries after sometime of the creation of the same file, During this time file will be empty.

and how can i wait until something is written to the log and reason being based on the log entries i will be invoking different script!,

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;
}

Basically i am grepping some of the important information from the logs.


Solution

  • For such formulation of your question, something like this might help you:

    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
    }
    

    Read more here