Can I send STDOUT and STDERR to a log file and also to the screen in Win32 Perl?

Kurt W. Leucht picture Kurt W. Leucht · Oct 7, 2009 · Viewed 21.1k times · Source

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.

Answer

brian d foy picture brian d foy · Oct 7, 2009

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.