Redirecting STDOUT and STDERR to file in perl

A small issue, but very common. There are several methods to do it, here is my favorite, which lets you print to the ‘original’ streams:

my $log_file = "/path/to/log/file.log";
redirect_streams();
print "Hello log file!\n";
print OLDOUT "Hello console!\n";
restore_streams();
exit(0);
##############################################################
sub restore_streams
{
  close(STDOUT) || die "Can't close STDOUT: $!";
  close(STDERR) || die "Can't close STDERR: $!";
  open(STDERR, ">&OLDERR") || die "Can't restore stderr: $!";
  open(STDOUT, ">&OLDOUT") || die "Can't restore stdout: $!";
}
##############################################################
sub redirect_streams
{
  open OLDOUT,">&STDOUT" || die "Can't duplicate STDOUT: $!";
  open OLDERR,">&STDERR" || die "Can't duplicate STDERR: $!";
  open(STDOUT,">> $log_file");
  open(STDERR,">&STDOUT");
}

 

Advertisements