Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 885
Kurt W. Leucht Avatar asked Oct 07 '09 15:10

Kurt W. Leucht


People also ask

Can you redirect stdout and stderr to the same file?

When saving the program's output to a file, it is quite common to redirect stderr to stdout so that you can have everything in a single file. > file redirect the stdout to file , and 2>&1 redirect the stderr to the current location of stdout .

Should logs go to stdout or stderr?

As mentioned in #6099: all log messages should go to stderr instead of stdout. command API related output should use a dedicated interface that outputs to stdout.


2 Answers

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.

like image 142
brian d foy Avatar answered Sep 23 '22 03:09

brian d foy


use PerlIO::Util;
*STDOUT->push_layer(tee => ">>/dir/dir/file");
*STDERR->push_layer(tee => ">>/dir/dir/file");

Though I use Log::Dispatch extensively, I've used the above to log what actually got displayed to the screen to a file.

like image 33
Oesor Avatar answered Sep 24 '22 03:09

Oesor