Monday, September 14, 2009

Logging: helpful perl snippet to start with

I needed to establish simple logging in my small perl app which serves as a plugin for a company "big" product. Here is what I have come up with:


use strict;

my $log_file=file_string_here;

my $LOG_HANDLE = open_log_file_for_writing($log_file);

log_entry($LOG_HANDLE, "Logging started");

log_entry($LOG_HANDLE, "Logging finished");

close_log_file($LOG_HANDLE);


sub open_log_file_for_writing
{
my $log_file = shift;
my $LOGGING_HANDLE;

print "INFO Opening log file...\n";

unless(open $LOGGING_HANDLE, ">> ", $log_file) {
return undef;
}

my $current_time = localtime;
print $LOGGING_HANDLE "\n".$current_time."\n";

return $LOGGING_HANDLE;
}

sub log_entry
{
my $LOGGING_HANDLE = shift;
my $log_entry = shift;

print $LOGGING_HANDLE $log_entry."\n";
}

sub close_log_file
{
my $LOGGING_HANDLE = shift;
print "INFO Closing log file...\n";
close($LOGGING_HANDLE);
}




upd: the logging handle can be externalized for easing the use of the logging. It comes at cost of global variable, but might still suit moderately sized perl-scripts. Code will change a bit:


my $g_LOGGING_HANDLE = open_log_file_for_writing($log_file);
log_entry("Logging started");

sub log_entry
{
my $log_entry = shift;

print $g_LOGGING_HANDLE $log_entry."\n";
}


Now you can call log("log entry goes here") from where you want quickly, without the need to pass down as well the logging handle, for example deep inside some procedure or function.

upd1: If you want to control whether to log or not, another small modification will do it for you:


my $LOG_ENABLED = 1; # put 1 to enable logging, 0 to disable logging

my $log_file = "plugin_request.log";
...

my $g_LOGGING_HANDLE;
undef $g_LOGGING_HANDLE;

if ($LOG_ENABLED)
{
$g_LOGGING_HANDLE = open_log_file_for_writing($log_file);
}


...

sub log_entry
{
my $log_entry = shift;

return if (!defined($g_LOGGING_HANDLE));

print $g_LOGGING_HANDLE $log_entry."\n";
}

sub close_log_file
{
my $LOGGING_HANDLE = shift;

return if (!defined($g_LOGGING_HANDLE));

print "INFO Closing log file...\n";
close($LOGGING_HANDLE);
}

No comments: