not-a-monk has asked for the wisdom of the Perl Monks concerning the following question:

I would like to create a log file that records everything my program prints to the terminal, but I also want to be able to write verbose info to that log file which wouldn't get sent to the terminal. It was suggested to me to try the POSIX 'tee' command as such:
#!/usr/bin/perl open(STDERR,">&STDOUT"); # Redirect IO select(STDOUT); $| = 1; # Unbuffered output # Set the path and format of the name for z_brian's log file $logfileName = sprintf("$ENV{LTMP}/z_brian_%02d\_%02d\_%02d.log", $yea +r, $mon, $mday); # Write everything that goes to standard out also to the log file open(STDOUT, "| tee -ai $logfileName"); # Open a file handle to that same log file to also write verbose info +to open(my $LOGFILE, ">>", $logfileName) or die $!; print "Welcome user!\n"; print $LOGFILE "log msg 1\n"; print STDOUT "out msg 1\n"; print $LOGFILE "log msg 2\n"; print STDERR "err msg 1\n"; print $LOGFILE "log msg 3\n"; print "out msg 2\n"; print $LOGFILE "log msg 4\n"; print "Goodbye user!\n"; print $LOGFILE "log msg 5\n";
This code does not work as I would like. The result on the terminal is correct except for STDERR (but I can live with that if needed). However, the log file displays all of the data I write to the log file before all the data I write to STDOUT, and I want to preserve the order so I can do 'tail -f' to see log file additions in real-time.

Replies are listed 'Best First'.
Re: tee and log files
by salva (Canon) on May 18, 2012 at 14:08 UTC
    use File::Tee:
    use File::Tee qw(tee); open my $LOGFILE, '>>', $logFileName or die $!; tee STDOUT, '>>&', $LOGFILE or die $!; ...
    update: I am thinking that this is not going to work properly either, because the tee work is done by a subprocess and so there is a race condition.

    In this case, IO::Tee that uses a tied file handle to duplicate the output may be a better option.

      Thank you for your suggestions but due to my circumstances I am trying to implement this solution without using CPAN or similar non-standard libraries.