Set a Logging Variable
Usually I do this at the beginning of the script, but it can change according to what I'm doing. A simple
my $logging=1
That way I can change the declaration to undef at any point and turn logging off.
Conditionally Open and Close the Logfile
At the earliest reasonable time, open the logfile in append mode:if($logging){open FILE , ">>./my.log";}
At the latest possible time, close the logfile
if($logging){close FILE};
Don't forget to close the logfile as part of your error handling routines as well. Perl cleans things up nicely for you, but there are always exceptions to those kinds of rules.
Logging Subroutine
A simple subroutine to enable logging as follows:sub logit{
if ($logging){
print FILE "$_[0]\n";
}
}
It prints whatever it receives in the first parameter to the log file. If you need to print something simple, just call "logit('text to log');" and your log entry will be created. For complex objects, I frequently use something like logit(Dumper($complex)); (of course, including the module Data::Dumper).
What visitors have to say about Simple Logging in Perl
