Perl Message Logging

The following code is a quick and dirty, but nevertheless usefull snippet to add logging facility to any perl script. You might want to add additional severities at lines 2-6, change the timestamp format at line 14, or enable logging into a file at lines 42-54.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Defines severities of messages to log
my %TYPES = (
   ERROR => 1,
   DEBUG => 1,
   INFO  => 1
);
 
# Creates the time string for log messages
# Usage: getTimestring($unixTimeValue)
sub getTimestring {
   my $t = shift;
   $t = time if !$t;
   my @T = localtime($t);
   my $time = sprintf("%02d/%02d/%04d %02d:%02d:%02d",
              $T[3], $T[4]+1, $T[5]+1900, $T[2], $T[1], $T[0]);
   return $time;
}
 
# logs an error message
# Usage: logError($message);
sub logError {
   my $s = shift;
   logEntry($s, 'ERROR');
}
 
# logs an information message
# Usage: logInfo($message);
sub logInfo {
   my $s = shift;
   logEntry($s, 'INFO');
}
 
# logs a debug message
# Usage: logDebug($message);
sub logDebug {
   my $s = shift;
   logEntry($s, 'DEBUG');
}
 
# logs a single entry with given message severity
# Usage: logEntry($message, $severity);
sub logEntry {
   my $s = shift;
   my $type = shift;
   return if !$TYPES{$type};
 
   # build timestamp and string
   $type = rpad($type, 5);
   my $time = getTimestring();
   $s =~ s/\n/\n$time $type - /g;
 
   # print to STDOUT if required
   print "$time $type - $s\n";
}
 
# Right pads a string
# Usage: rpad($string, $maxlen[, $padchar]);
sub rpad {
   my $s = shift;
   my $len = shift;
   my $char = shift;
 
   $char = ' ' if !$char;
   $s .= $char while (length($s) < $len);
   return $s;
}

Tags:

Leave a Reply