blib/lib/Event/RPC/Logger.pm untested

filter: Statementstmt 0.0% 0 / 66 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 113 CC 11 SCAR 27.3
CC
11
Cov
0%
log
42.0
new
12.0
remove_fh
12.0
CRAP 15.4
1 # $Id: Logger.pm,v 1.5 2006/04/23 08:37:41 joern Exp $
2  
3 #-----------------------------------------------------------------------
4 # Copyright (C) 2002-2006 Jörn Reder <joern AT zyn.de>.
5 # All Rights Reserved. See file COPYRIGHT for details.
6 #
7 # This module is part of Event::RPC, which is free software; you can
8 # redistribute it and/or modify it under the same terms as Perl itself.
9 #-----------------------------------------------------------------------
10  
11 package Event::RPC::Logger;
12  
13 use strict;
14 use FileHandle;
15  
16 sub get_filename { shift->{filename} }
17 sub get_filename_fh { shift->{filename_fh} }
18  
19 sub get_fh_lref { shift->{fh_lref} }
20 sub get_min_level { shift->{min_level} }
21  
22 sub set_fh_lref { shift->{fh_lref} = $_[1] }
23 sub set_min_level { shift->{min_level} = $_[1] }
24  
25  
26 sub new {
27 my $class = shift;
28 my %par = @_;
29 my ($filename, $fh_lref, $min_level) =
30 @par{'filename','fh_lref','min_level'};
31  
32 my $filename_fh;
33 if ( $filename ) {
34 $filename_fh = FileHandle->new;
35 open ($filename_fh, ">>$filename")
36 or die "can't write log $filename";
37 $filename_fh->autoflush(1);
38 }
39  
40 if ( $fh_lref ) {
41 foreach my $fh ( @{$fh_lref} ) {
42 my $old_fh = select $fh;
43 $| = 1;
44 select $old_fh;
45 }
46 } else {
47 $fh_lref = [];
48 }
49  
50 my $self = bless {
51 filename => $filename,
52 filename_fh => $filename_fh,
53 fh_lref => $fh_lref,
54 min_level => $min_level,
55 }, $class;
56
57 return $self;
58 }
59  
60 sub DESTROY {
61 my $self = shift;
62
63 my $filename_fh = $self->get_filename_fh;
64 close $filename_fh if $filename_fh;
65  
66 1;
67 }
68  
69 sub log {
70 my $self = shift;
71 my ($level, $msg);
72 if ( @_ == 2 ) {
73 $level = $_[0];
74 $msg = $_[1];
75 } else {
76 $level = 1;
77 $msg = $_[0];
78 }
79  
80 return if $level > $self->get_min_level;
81
82 $msg .= "\n" if $msg !~ /\n$/;
83  
84 my $str = localtime(time)." [$level] $msg";
85  
86 for my $fh ( @{$self->get_fh_lref} ) {
87 print $fh $str if $fh;
88 }
89  
90 my $fh = $self->get_filename_fh;
91 print $fh $str if $fh;
92  
93 1;
94 }
95  
96 sub add_fh {
97 my $self = shift;
98 my ($fh) = @_;
99  
100 push @{$self->get_fh_lref}, $fh;
101  
102 1;
103 }
104  
105 sub remove_fh {
106 my $self = shift;
107 my ($fh) = @_;
108  
109 my $fh_lref = $self->get_fh_lref;
110  
111 my $i;
112 for ( $i=0; $i<@{$fh_lref}; ++$i ) {
113 last if $fh_lref->[$i] eq $fh;
114 }
115  
116 return if $i == @{$fh_lref};
117 splice @{$fh_lref}, $i, 1;
118
119 1;
120 }
121  
122 1;
123  
124 __END__