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.
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |