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

How can I redirect the process output (not the actual output) to a .log file in a perl script? I have a script which runs to compile some files recurssively. Instead of writing out the process to the screen, i need to redirect it automatically to a .log file or something, which holds the imformation of what has happened during the whole process of recusrssive compiling of the files. Please note that I am not trying redirect the actual output (which is the compiled files or the results of the compilation) to the ,log file. In essence the ,log or the out file should have something like:

Script started...
command is script.pl <file(s)>....
Compiling...
Error:.... (if any)
resuming compiling...
done.

At present the above output is printed to the screen. Please advise and thanx for the help.

Replies are listed 'Best First'.
Re: Process output redirecting
by Chmrr (Vicar) on Apr 23, 2001 at 02:52 UTC

    A few simple steps:

    1. At the top of your program, open LOGFILE, ">somefilename.log" or die "Can't write logfile: $!";
    2. After that, select LOGFILE; to make all of your prints go to LOGFILE instead of STDOUT
    3. At the bottom of the program, don't forget to close LOGFILE or die "Can't close logfile: $!";

    Look up open, select, and close for some more details.

     
    perl -e 'print "I love $^X$\"$]!$/"#$&V"+@( NO CARRIER'

Re: Process output redirecting
by BMaximus (Chaplain) on Apr 23, 2001 at 03:19 UTC
    You could also do:
    script.pl >logfile.txt 2>&1

    Which will redirect the standard and error output to the logfile. That's the simple and easy way. Not the best way though.

    Or you can:
    close(STDOUT); close(STDERR); open(STDOUT , ">logfile.txt") or die "Can't open logfile: $!\n"; # now anything that is printed will go to the logfile unless # its given another filehandle. Just be sure to close the # handle before the program exits. ... # program end close(STDOUT);

    Hope this answers your question.

    BMaximus
      I second BMaximus' suggestion of redirecting a standard filehandle like STDOUT to a log file.

      However, I would suggest you keep STDOUT open as-is, and redirect STDERR instead. That way normal program output (via print) behaves like it always does, but warn and die output to your log file.

        Even better, use Tom Christiansen's implementation of Tie::Tee that he gives here...

        (There is also an IO::Tee, but it doesn't work like I would want. Yes, I am sending a bug report to the author.)

Re: Process output redirecting
by buckaduck (Chaplain) on Apr 23, 2001 at 12:14 UTC
    There are a few answers provided to this FAQ at this node within the Input and Output section of the Q&A area of PerlMonks. Happy hunting!

    buckaduck