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:

  1. use strict;  
  2.   
  3. my $log_file=file_string_here;  
  4.   
  5. my $LOG_HANDLE = open_log_file_for_writing($log_file);  
  6.   
  7. log_entry($LOG_HANDLE"Logging started");  
  8.   
  9. log_entry($LOG_HANDLE"Logging finished");  
  10.   
  11. close_log_file($LOG_HANDLE);  
  12.   
  13.   
  14. sub open_log_file_for_writing  
  15. {  
  16.    my $log_file = shift;  
  17.    my $LOGGING_HANDLE;  
  18.   
  19.    print "INFO Opening log file...\n";  
  20.   
  21.    unless(open $LOGGING_HANDLE">> "$log_file) {  
  22.       return undef;  
  23.    }  
  24.   
  25.    my $current_time = localtime;  
  26.    print $LOGGING_HANDLE "\n".$current_time."\n";  
  27.   
  28.    return $LOGGING_HANDLE;  
  29. }  
  30.   
  31. sub log_entry  
  32. {  
  33.    my $LOGGING_HANDLE = shift;  
  34.    my $log_entry      = shift;  
  35.   
  36.    print $LOGGING_HANDLE $log_entry."\n";  
  37. }  
  38.   
  39. sub close_log_file  
  40. {  
  41.    my $LOGGING_HANDLE = shift;  
  42.    print "INFO Closing log file...\n";  
  43.    close($LOGGING_HANDLE);  
  44. }  



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:

  1. my $g_LOGGING_HANDLE = open_log_file_for_writing($log_file);  
  2. log_entry("Logging started");  
  3.   
  4. sub log_entry  
  5. {  
  6.    my $log_entry      = shift;  
  7.   
  8.    print $g_LOGGING_HANDLE $log_entry."\n";  
  9. }  


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:

  1. my $LOG_ENABLED = 1; # put 1 to enable logging, 0 to disable logging  
  2.   
  3. my $log_file = "plugin_request.log";  
  4. ...  
  5.   
  6. my $g_LOGGING_HANDLE;  
  7. undef $g_LOGGING_HANDLE;  
  8.   
  9. if ($LOG_ENABLED)  
  10. {  
  11.    $g_LOGGING_HANDLE = open_log_file_for_writing($log_file);  
  12. }  
  13.   
  14.   
  15. ...  
  16.   
  17. sub log_entry  
  18. {  
  19.    my $log_entry      = shift;  
  20.   
  21.    return if (!defined($g_LOGGING_HANDLE));  
  22.   
  23.    print $g_LOGGING_HANDLE $log_entry."\n";  
  24. }  
  25.   
  26. sub close_log_file  
  27. {  
  28.    my $LOGGING_HANDLE = shift;  
  29.   
  30.    return if (!defined($g_LOGGING_HANDLE));  
  31.   
  32.    print "INFO Closing log file...\n";  
  33.    close($LOGGING_HANDLE);  
  34. }  

No comments: