isotope has asked for the wisdom of the Perl Monks concerning the following question:

I have an application where I would like to capture STDOUT and STDERR to files, given references to their filehandles... Ideally I would tee them so shell redirection would still work. Here are some relevant code snippets:

The code that actually opens the file and returns the filehandle reference:
sub open_logfile { my $filename = shift; # Our filehandle reference object local *FH; # Attempt to open the file if(open(FH, "> " . $filename)) { # Opened the file print $FH_STATUS "Opened logfile: " . $filename . "\n"; select(FH); $| = 1; # Unbuffer select(STDOUT); # Restore default print to STDOUT return *FH; # Return the new fh reference } else { # Couldn't open the file... print $FH_ERROR "Problem opening logfile: \n"; print $FH_ERROR $filename . ":\n"; print $FH_ERROR $! . "\n"; print $FH_ERROR "Redirecting logging to Error log\n\n"; sleep 5; return $FH_ERROR; } }

Code that I would likely use to tee the output:
use IO::Tee; $FH_STATUS = new IO::Tee(\*STDOUT, new_logfile(name_logfile('logs/QTStatus')));

And then redirect all STDOUT to the new $FH_STATUS. If I can get that working, I'll do the same with STDERR.

--isotope
http://www.skylab.org/~isotope/

Replies are listed 'Best First'.
Re: Teeing STDOUT and STDERR to files using filehandle references
by isotope (Deacon) on Dec 16, 2000 at 04:03 UTC
Re: Teeing STDOUT and STDERR to files using filehandle references
by isotope (Deacon) on Dec 16, 2000 at 01:03 UTC
      How about dupping the filehandle:
      sub open_logfile { my $filename = shift; open STDOUTBACK, '>&STDOUT' or die "Can't dup STDOUT\n"; open STDOUT, '> ' . $filename or die "can't write to $filename: $!\n +"; }
      In this case any attempt to print "foo\n" or print STDOUT "foo\n" will go to the logfile.

      Or just use select:

      sub open_logfile { my $filename = shift; open FH, '> ' . $filename or die "Can't write to $filename: $!\n"; select FH; }
      In the second case print "foo\n" will print where you want but print STDOUT "foo\n" will still go to the real STDOUT.
        This is correct, but it's not the solution to my problem... I'm redirecting to existing filehandles, not opening new files.

        --isotope
        http://www.skylab.org/~isotope/
      check perltie for tying file handles... there's also IO::Handle for that task.
      --
      Casey
         I am a superhero.