Venkatesan
Venkatesan

Reputation: 442

Using a common log file in multi thread perl program

I have tried the below code to write common log in multi threaded program and have to cut the file and create the new one if it reaches 3mb.Below code after it reaches 3mb creates the new file, but the already opened file which is to be closed was not closing,in that file alone all the threads are writing,in new log file only one thread able to write.Can anyone please help me how to solve this problem.I want to create a new common log file everytime when it reaches 3mb in multithreaded program.

use strict;
use warnings;
use threads;
use POSIX qw(strftime);


my $count;
my $thread_count=5;
my @threads;
my $date_string = strftime "%Y%m%d\_%H\_%M\_%S",localtime;
my $log_file_name="log\_$date_string.log";

open(LOG,"+>","log\_$date_string.log")or die "cant open the file";


for ($count = 1; $count <=$thread_count ; $count++) 
{
    my $thread = threads->new(\&process);
    push(@threads,$thread);        

}

foreach (@threads) 
{
   $_->join;
}
close LOG;

sub process
{  
   for(1..100000)
   {
       my $id=threads->tid(); 

        print LOG "$id I need a perl script using multi thread to write a common log file and when the file becomes of 3mb it should be closed and new common log file should be created \n.";

    if(stat("$log_file_name")->size >(3*1024*10240))
    {
         close LOG;
         $date_string = strftime "%Y%m%d\_%H\_%M\_%S",localtime;
         $log_file_name="log\_$date_string.log";
         open(LOG,"+>","log\_$date_string.log")or die "cant open the file";                  
    }

   }

}

Upvotes: 0

Views: 693

Answers (1)

Pradeep
Pradeep

Reputation: 3153

I have used Log::Log4Perl in many parallel processes, works like a charm, try this http://search.cpan.org/perldoc?Log%3A%3ALog4perl

Upvotes: 2

Related Questions