欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

perl的logwrapper使用实例代码

程序员文章站 2022-12-31 14:10:00
这里为大家举二个小例子,供朋友们学习参考。 对任何的函数记录函数运行的时间。复制代码 代码如下:#!/usr/bin/perluse warnings;use stric...

这里为大家举二个小例子,供朋友们学习参考。

对任何的函数记录函数运行的时间。

复制代码 代码如下:

#!/usr/bin/perl
use warnings;
use strict;
no strict "refs";
sub testlogtostd{
print "test stdout : \n";
open log,"> 2.txt";
select log;
print "just a test\n";
#recover stdout
select stdout;
print "just a test2\n";
close log;
}
sub testfun{
  print "from testfun\n";
  print stderr "from testfun error\n";
}
sub testfun2{
  my $arg1 = shift;
  my $arg2 = shift;
  print "from testfun2\n";
  print $arg1."\n";
  print $arg2."\n";
}
my $log_root = "log" if(! $3 ||$3 == "");
my $ret = system("mkdir $log_root") if(! -e $log_root);
my $report_log = "$log_root/report.log";
open my $reportlog,">",$report_log or die "cannot not open log file report.log\n";
sub logwrapper{
  my $log_root = shift;
  my $reportlog  = shift;
  my $fun = shift;
  my @parameters = @_;
  *old_stdout = *stdout;
  *old_stderr = *stderr;
  open log, ">","$log_root/$fun.log" or die "annot open log file $fun.\n";
  *stdout = *log;
  *stderr = *log;
  my $start = time;
  my $ret = &$fun(@parameters);
  my $end = time;
  *stdout = *old_stdout;
  *stderr = *old_stderr;
  close log;
  my $duration = $end - $start;
  print $reportlog "$fun\n";
  print $reportlog "start:".localtime($start)."\n";
  print $reportlog "end:".localtime($end)."\n";
  print $reportlog "duration:".formattimeduration($duration)."\n";
  print $reportlog "result:$ret\n";
  print $reportlog "\n";
  print $reportlog "\n";
}
sub formattimeduration($){
  my $t = shift;
  my $hrs = int($t/3600);
  my $mins = int($t%3600/60);
  my $secs = int($t%3600%60);
  return "$hrs:$mins:$secs";
}
&logwrapper($log_root,$reportlog,"testfun");
&logwrapper($log_root,$reportlog,"testfun2","arg1","arg2");
print "thanks\n";

若需要调用外部命令,则需要如下:

复制代码 代码如下:

#!/usr/bin/perl
use strict;
use warnings;
# run external commands
# redirect stdout and stderr
sub run_cmd{
  my $cmd = shift;
  my $pid = open(ph, "$cmd 2>&1 |");
  while (<ph>) {print $_; }
}
open(fh, ">", "perl-test.log");
*old_stdout = *stdout;
*old_stderr = *stderr;
*stdout = *fh;
*stderr = *fh;
my $ret = undef;
$ret = readpipe("cp a b ");
$ret = system("cp a b");
$ret = `cp a b`;
run_cmd("cp a b");
print "aa";
print stderr "bb";
*stdout = *old_stdout;
*stderr = *old_stderr;