标签:
来源:
http://www.cnblogs.com/itech/archive/2012/09/22/2698385.html
对任何的函数将标准输出和错误输出重定向到对应的log文件。
对任何的函数记录函数运行的时间。
代码:
1 #!/usr/bin/perl 2 use warnings; 3 use strict; 4 no strict "refs"; 5 6 sub testLogToStd{ 7 print "Test stdout : \n"; 8 open LOG,"> 2.txt"; 9 select LOG; 10 print "just a test\n"; 11 #recover STDOUT 12 select STDOUT; 13 print "just a test2\n"; 14 close LOG; 15 } 16 17 sub testFun{ 18 print "From testFun\n"; 19 print STDERR "From TestFun Error\n"; 20 } 21 sub testFun2{ 22 my $arg1 = shift; 23 my $arg2 = shift; 24 print "From testFun2\n"; 25 print $arg1."\n"; 26 print $arg2."\n"; 27 } 28 29 my $log_root = "log" if(! $3 ||$3 == ""); 30 my $ret = system("mkdir $log_root") if(! -e $log_root); 31 my $report_log = "$log_root/report.log"; 32 open my $REPORTLOG,">",$report_log or die "cannot not open log file report.log\n"; 33 34 sub logWrapper{ 35 my $log_root = shift; 36 my $REPORTLOG = shift; 37 my $fun = shift; 38 my @parameters = @_; 39 *old_stdout = *STDOUT; 40 *old_stderr = *STDERR; 41 open LOG, ">","$log_root/$fun.log" or die "annot open log file $fun.\n"; 42 *STDOUT = *LOG; 43 *STDERR = *LOG; 44 my $start = time; 45 my $ret = &$fun(@parameters); 46 my $end = time; 47 *STDOUT = *old_stdout; 48 *STDERR = *old_stderr; 49 close LOG; 50 51 my $duration = $end - $start; 52 print $REPORTLOG "$fun\n"; 53 print $REPORTLOG "start:".localtime($start)."\n"; 54 print $REPORTLOG "end:".localtime($end)."\n"; 55 print $REPORTLOG "duration:".formatTimeDuration($duration)."\n"; 56 print $REPORTLOG "result:$ret\n"; 57 print $REPORTLOG "\n"; 58 print $REPORTLOG "\n"; 59 } 60 61 sub formatTimeDuration($){ 62 my $t = shift; 63 my $hrs = int($t/3600); 64 my $mins = int($t%3600/60); 65 my $secs = int($t%3600%60); 66 return "$hrs:$mins:$secs"; 67 } 68 69 70 &logWrapper($log_root,$REPORTLOG,"testFun"); 71 &logWrapper($log_root,$REPORTLOG,"testFun2","arg1","arg2");
print "thanks\n";
如果需要调用外部命令需要如下:
1 use strict; 2 use warnings; 3 4 # run external commands 5 # redirect stdout and stderr 6 sub run_cmd{ 7 my $cmd = shift; 8 my $pid = open(PH, "$cmd 2>&1 |"); 9 while (<PH>) {print $_; } 10 } 11 12 open(FH, ">", "perl-test.log"); 13 *old_stdout = *STDOUT; 14 *old_stderr = *STDERR; 15 *STDOUT = *FH; 16 *STDERR = *FH; 17 my $ret = undef; 18 $ret = readpipe("cp a b "); 19 $ret = system("cp a b"); 20 $ret = `cp a b`; 21 run_cmd("cp a b"); 22 print "AA"; 23 print STDERR "BB"; 24 *STDOUT = *old_stdout; 25 *STDERR = *old_stderr;
标签:
原文地址:http://www.cnblogs.com/spriteflk/p/5741099.html