File Coverage

blib/lib/Sub/Daemon/Log.pm
Criterion Covered Total %
statement 32 43 74.4
branch 2 8 25.0
condition 1 2 50.0
subroutine 9 13 69.2
pod 0 9 0.0
total 44 75 58.6


line stmt bran cond sub pod time code
1             package Sub::Daemon::Log;
2            
3 3     3   41 use Fcntl qw(:flock);
  3         8  
  3         330  
4 3     3   21 use Carp;
  3         6  
  3         207  
5            
6 3     3   20 use constant LEVEL => {debug => 1, info => 2, warn => 3, error => 4, fatal => 5};
  3         6  
  3         2178  
7            
8             sub new {
9 2     2 0 76 my $class = shift;
10 2         12 my %opts = (
11             path => undef,
12             level => 'debug',
13             @_,
14             );
15            
16 2         10 my $self = bless \%opts, $class;
17             }
18            
19             sub debug {
20 0     0 0 0 $self = shift;
21 0         0 $self->log('debug', @_);
22             }
23            
24             sub info {
25 5     5 0 204 $self = shift;
26 5         37 $self->log('info', @_);
27             }
28            
29             sub warn {
30 3     3 0 140 $self = shift;
31 3         18 $self->log('warn', @_);
32             }
33            
34             sub error {
35 0     0 0 0 $self = shift;
36 0         0 $self->log('error', @_);
37             }
38            
39             sub fatal {
40 0     0 0 0 $self = shift;
41 0         0 $self->log('fatal', @_);
42             }
43            
44             sub _default {
45 8     8   29 my $self = shift;
46 8         41 my ($time, $level) = (shift, shift);
47 8         487 my ($s, $m, $h, $day, $month, $year) = localtime $time;
48 8   50     368 $time = sprintf '%04d-%02d-%02d %02d:%02d:%08.5f', $year + 1900, $month + 1,
49             $day, $h, $m, "$s." . ((split /\./, $time)[1] // 0);
50 8         120 return "[$time] [$$] [$level] " . join "\n", @_, '';
51             }
52            
53             sub log {
54 8     8 0 57 my ($self, $level) = (shift, shift);
55 8 50       89 return if LEVEL()->{$self->{level}} > LEVEL()->{$level};
56 8         41 my $str = $self->_default(time(),$level,@_);
57 8         40 my $handle = $self->handle;
58            
59 8         129 flock $handle, LOCK_EX;
60 8         163 print $handle $str;
61 8         384 flock $handle, LOCK_UN;
62             #$self->append($str);
63             }
64            
65             sub handle {
66 8     8 0 23 my $self = shift;
67 8 50       43 my $path = $self->{path} or return \*STDERR;
68 8         637 open my $fi, '>>' . $path;
69 8         75 return $fi;
70             }
71            
72             sub append {
73 0     0 0   my ($self, $msg) = @_;
74 0 0         return unless my $handle = $self->handle;
75 0           flock $handle, LOCK_EX;
76 0 0         print($handle encode('UTF-8', $msg)) or croak "Can't write to log: $!";
77 0           flock $handle, LOCK_UN;
78             }
79            
80             1;