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.

In reply to tee and log files by not-a-monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.