spikey_wan has asked for the wisdom of the Perl Monks concerning the following question:
I have an existing script that's rather large and contains many, many print commands. It's got a Tk GUI, but it logs things in the DOS console window.
Since completing it, I've realised that it would be nice to give the user the opportunity to log everything that's printed to the console window to a file.
I have managed to work out that I can print to the screen and a file by using:
So, is there a way that I can call a sub that will turn file logging on and off, or must I find every print statement, and replace it, like this?use IO::Tee; my $tee = IO::Tee -> new(">stdout.txt", \*STDOUT); print $tee "Cheese!\n";
Thanks,my $log = 0; print "Do you want to log to a file?"; my $resp = <STDIN>; if ($resp =~ /^y/i) { $log = IO::Tee -> new(">stdout.txt", \*STDOUT); } ... if $log { print $log "What did I want to say?\n" } else { print "What did I want to say?\n" }
NEW UPDATE:
I've now found a much better solution, that doesn't need any fiddling about with changing print commands. Actually, it's so obvious, I don't know how I missed it in the first place!
OLD UPDATE:my $tee; sub log_to_file { my ($on, $logfile) = @_; if ($on) { $tee = IO::Tee->new(">>$logfile", \*STDOUT); select $tee; print "Logging console window to $logfile\n"; } else { print "Console window log OFF.\n"; undef $tee; select STDOUT; close $logfile; } }
Since reading ccn's response (ccn++), I have come up with the following sub to turn file logging on and off:
Then all I did was to search for all print commands, and replaced them with DEBUG. Really cool, thanks ccn!sub log_to_file { my $on = $_[0]; if ($on) { Log::Log4perl->easy_init ({ level => $DEBUG, file => 'STDOUT', layout => '%m', }, {level => $DEBUG, file => ">> $console_log", layout => '%m', }); } else { Log::Log4perl->easy_init ({ level => $DEBUG, file => 'STDOUT', layout => '%m', }); } }
The only thing I'm now trying to do is incorporate STDERR into the process, but I've had no success, so far.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Redirecting STDOUT to file and screen as an afterthought, on Windows.
by ccn (Vicar) on Nov 03, 2004 at 14:53 UTC | |
|
Re: Redirecting STDOUT to file and screen as an afterthought, on Windows.
by hlen (Beadle) on Nov 03, 2004 at 15:35 UTC | |
|
Re: Redirecting STDOUT to file and screen as an afterthought, on Windows.
by LanceDeeply (Chaplain) on Nov 03, 2004 at 16:00 UTC | |
|
Re: Redirecting STDOUT to file and screen as an afterthought, on Windows.
by TedPride (Priest) on Nov 04, 2004 at 07:19 UTC | |
by spikey_wan (Scribe) on Nov 04, 2004 at 10:44 UTC | |
by spikey_wan (Scribe) on Nov 04, 2004 at 13:54 UTC |