in reply to Print STDOUT and STDERR to file and to screen

Try this. It's sending STDOUT to log or STDERR to log if there's an error:

#!/usr/bin/perl use strict; use warnings; use diagnostics; open(LOG, '>', 'LOG_FILE') or die "Can't redirect stdout: $!"; open(CMD, 'ls |'); open(STDERR, '>&', STDOUT) or die "Can't redirect stderr: $!"; open(STDERR, '>', 'LOG_FILE') or die "Can't redirect stderr: $!"; print "LOG_FILE\n"; while (<CMD>) { &lprint ($_) } sub lprint { my ($line) = @_; print LOG $line; print $line; } close(CMD) or die "close CMD failed: $!"; exit(1);
Update: Fixed a typo

Replies are listed 'Best First'.
Re^2: Print STDOUT and STDERR to file and to screen
by Noame (Beadle) on Aug 03, 2009 at 07:15 UTC
    Thanks a lot - that what i need.

      Can you not simply redirect STDERR / STDOUT?
      This example (from the camel i think) redirects errors into a FH and to stdout. so you still get them on screen and in a logfile. You would only then need to rediirect STDOUT as shown above?

      sub make_log{ # make a log file my $log = shift; # open the log and stamp it open (my $log_file, '>>', $log) || die "Failed to open $log:\n$!"; print $log_file "\n------> log for $0\n------> ".scalar(localtime) +."\n\n"; # make sure errors are put into the logfile # i.e. print STDERR "weird" ~ not in logfile # warn "freaky" ~ in logfile (and the screen) # die "AAaaarrrrrgh!" ~ in logfile $SIG{__WARN__} = sub {print $log_file @_;print STDOUT @_}; $SIG{__DIE__} = sub {print $log_file @_;print STDOUT @_;exit 1}; # return complete return $log_file; }
      Just a something something...