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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s