How to redirect STDOUT and STDERR to a log file in Perl?

Possible duplicate:
Can I send STDOUT and STDERR to the log file, as well as to the screen in Win32 Perl?

I would like to redirect STDOUT, STDERR to temp_log and then to the logfile.txt file after the process is complete. The process runs for a full 20 minutes, so I would like to set temp_log during the execution of the process.

+3
source share
2 answers

STDOUTand STDERR- these are only file descriptors that are initialized with the standard output and error of your program, but they can be reassigned at any time for any reason. To do this, you want to keep the original settings in order to restore them.

sub process_that_writes_to_temp_log {

    # save original settings. You could also use lexical typeglobs.
    *OLD_STDOUT = *STDOUT;
    *OLD_STDERR = *STDERR;

    # reassign STDOUT, STDERR
    open my $log_fh, '>>', '/logdirectory/the-log-file';
    *STDOUT = $log_fh;
    *STDERR = $log_fh;

    # ... 
    # run some other code. STDOUT/STDERR are now redirected to log file
    # ...

    # done, restore STDOUT/STDERR
    *STDOUT = *OLD_STDOUT;
    *STDERR = *OLD_STDERR;
}

, , STDOUT/STDERR , local.

sub routine_that_writes_to_log {
    open my $log_fh, '>>', 'log-file';
    local *STDOUT = $log_fh;
    local *STDERR = $log_fh;

    # now STDOUT,STDERR write to log file until this subroutine ends.
    # ...

}
+8

STDOUT STDERR , Win32 Perl?. , "Win32", Perl.

, , , .

+4

Source: https://habr.com/ru/post/1767183/


All Articles