File Coverage

blib/lib/Alvis/Logger.pm
Criterion Covered Total %
statement 14 20 70.0
branch 3 6 50.0
condition n/a
subroutine 4 4 100.0
pod 0 2 0.0
total 21 32 65.6


line stmt bran cond sub pod time code
1             # $Id: Logger.pm,v 1.1 2005/06/17 15:45:56 mike Exp $
2              
3             # This is a simple logging object that I have accidentally implemented
4             # several different 90% subsets of in half a dozen different projects.
5             # It's time to get it done once, properly.
6              
7             package Alvis::Logger;
8 5     5   25 use strict;
  5         9  
  5         165  
9 5     5   29 use warnings;
  5         9  
  5         1410  
10              
11              
12             # Create a new logger object. Options that may be specified include:
13             # level [default 0]: only emit messages with priority less than
14             # or equal to this (so that the default behaviour is to
15             # be silent except for priority-zero messages, which are
16             # really error messages).
17             # stream [stderr]: where to write messages
18             #
19             sub new {
20 7     7 0 33 my $class = shift();
21             #warn("new($class): \@_ = ", join(", ", map { "'$_'" } @_), "\n");
22 7         108 my %options = ( level => 0, stream => \*STDERR, @_ );
23 7 100       153 $options{level} = 0 if !defined $options{level};
24              
25 7         145 return bless {
26             options => \%options,
27             }, $class;
28             }
29              
30              
31             # Log a message. The first argument is the priority of the message,
32             # the remainder are strings that will be concatenated to form the
33             # message.
34             #
35             sub log {
36 69     69 0 97 my $this = shift();
37 69         321 my($msglevel, @msg) = @_;
38              
39 69         166 my $level = $this->{options}->{level};
40 69 50       362 return if $msglevel > $level;
41              
42 0           my $stream = $this->{options}->{stream};
43 0           my $text = "log($msglevel): ";
44 0 0         if ($this->{options}->{timestamp}) {
45 0           my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
46             # ISO date format, which is big-endian and so sorts nicely
47 0           $text .= sprintf("%04d-%02d-%02d %02d:%02d:%02d: ",
48             $year+1900, $mon+1, $mday, $hour, $min, $sec);
49             }
50              
51 0           print $stream $text, @msg, "\n";
52             }
53              
54              
55             1;