STDOUT
and STDERR
are just filehandles that are initialized to your program's standard output and error, but they can be reassigned at any time for any reason. For this purpose, you will want to save the original settings so you can 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;
}
Depending on how your program is laid out, saving and restoring the old STDOUT/STDERR settings can be done automatically using 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.
# ...
}