【问题标题】:Using a common log file in multi thread perl program在多线程 perl 程序中使用通用日志文件
【发布时间】:2014-05-27 17:46:02
【问题描述】:

我已经尝试以下代码在多线程程序中编写通用日志,如果达到 3mb,则必须剪切文件并创建新文件。达到 3mb 后的以下代码会创建新文件,但是已经打开的文件是要关闭没有关闭,仅在该文件中所有线程都在写入,在新日志文件中只有一个线程能够写入。谁能帮我解决这个问题。我想每次都创建一个新的通用日志文件当它在多线程程序中达到 3mb 时。

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

   }

}

【问题讨论】:

    标签: multithreading perl


    【解决方案1】:

    我在许多并行进程中使用过 Log::Log4Perl,效果很好,试试这个http://search.cpan.org/perldoc?Log%3A%3ALog4perl

    【讨论】:

      猜你喜欢
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 2013-08-29
      相关资源
      最近更新 更多