Can I send STDOUT and STDERR to a log file and als

2019-01-24 05:30发布

I've searched the Internet and have found some good solutions for teeing STDOUT to 2 different places. Like to a log file and also to the screen at the same time. Here's one example:

use IO::Tee;
my $log_filename = "log.txt";
my $log_filehandle;
open( $log_filehandle, '>>', $log_filename )
  or die("Can't open $log_filename for append: $!");
my $tee = IO::Tee->new( $log_filehandle, \*STDOUT );
select $tee;

But this solution leaves STDERR going only to the screen and I want STDERR go to both the screen and also to the same log file that STDOUT is being logged to. Is that even possible?

My task is to get my build process logged, but I also want to see it on my IDE's screen as usual. And logging the error messages is just as important as logging the happy messages. And getting the errors logged to a separate log file is not a good solution.

8条回答
Summer. ? 凉城
2楼-- · 2019-01-24 05:57

try :

my logfh;
my $logfn = "some/path/to/file.log";
open ($logfh, '>',$logfn ) or die "Error opening logfile $logfn\n";
my $tee = IO::Tee->new( $logfh);
my $tee2 = IO::Tee->new( $logfh, \*STDOUT );
# all naked print statements will send output to log file
select($tee);
# all STDERR print statements will send output to console
*STDERR = *$tee2{IO};

All print statements that do not specify a file handle (that is, any regular messages) will send output to the log file. All print statements that use the STDERR file handle (that is, all errors) will send output to both the console and the log file.

查看更多
时光不老,我们不散
3楼-- · 2019-01-24 05:58

I use Log::Log4perl for things like this. It handles sending output to multiple places for you, including the screen, files, databases, or whatever else you like. Once you get even a little bit complex, you shouldn't be doing this stuff on your own.

Instead of printing to filehandles, you just give Log4perl a message and it figures out the rest. I have a short introduction to it in Mastering Perl. It's based on Log4j, and most of the stuff you can do in Log4j you can do in Log4perl, which also means that once you know it, it becomes a transferrable skill.

查看更多
登录 后发表回答