Redirects standard output and error output to the corresponding log file for any function.
Record the function running time for any function.
Code:
# ! /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";
To call an external command, you must:
Use Strict;
Use Warnings;
#Run External commands
# Redirect stdout and stderr
SubRun_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;
Complete!