Tiny.pm

filter: Statementstmt 90.0% 171 / 190 Branchbran 81.4% 57 / 70 Conditioncond 57.6% 15 / 26 MC/DCmcdc 35.2% 6 / 17 Subroutinesub 65.3% 34 / 52 Podpod 100% 8 / 8 totaltotal 80.1% 291 / 363 CC 49 SCAR 14.7
CC
49
Cov
85%
easy_init
11.8
new
8.1
would_log
8.0
CRAP 4.3
↑ Summary example.pl »
1 package Log::Tiny;
2  
3 16 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 16 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 16 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 16 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 16 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 16 our ($AUTOLOAD, $VERSION, $errstr, %formats, $caller_depth, $easy);
9  
10 # Extra caller frames to skip for the %F/%L/%P/%S formats. Wrapper
11 # authors can `local $Log::Tiny::caller_depth = 1;` (etc.) so those
12 # formats report their own caller rather than the wrapper.
13 16 $caller_depth = 0;
14  
15 =head1 NAME
16  
17 Log::Tiny - Log data with as little code as possible
18  
19 =head1 VERSION
20  
21 Version 1.3
22  
23 =cut
24  
25 16 $VERSION = '1.3';
26 16 $errstr = '';
27  
28 %formats = (
29 29 ▶ c => [ 's', sub { shift }, ], # category: AUTOLOAD
Subroutine __ANON__: called CC=1 SCAR=0.0
30 0 ▶ C => [ 's', sub { lc shift }, ], # lcategory: AUTOLOAD lc
Subroutine __ANON__: not called CC=1 SCAR=6.9
31 D => [ 's', \&__format_D, ], # strftime date: %D{...}
32 0 ▶ f => [ 's', sub { $0 }, ], # program_file: $0
Subroutine __ANON__: not called CC=1 SCAR=6.9
33 0 ▶ F => [ 's', sub { (caller(2 + $caller_depth))[1] }, ], # caller_file: caller
Subroutine __ANON__: not called CC=1 SCAR=6.9
34 0 ▶ g => [ 's', sub { scalar gmtime }, ], # gmtime: scalar gmtime
Subroutine __ANON__: not called CC=1 SCAR=6.9
35 0 ▶ L => [ 'd', sub { (caller(2 + $caller_depth))[2] }, ], # caller_line: caller
Subroutine __ANON__: not called CC=1 SCAR=6.9
36 29 ▶ m => [ 's', sub { shift; shift }, ], # message: args
Subroutine __ANON__: called CC=1 SCAR=0.0
37 12 ▶ n => [ 's', sub { $/ }, ], # newline: $/
Subroutine __ANON__: called CC=1 SCAR=0.0
38 0 ▶ o => [ 's', sub { $^O }, ], # osname: $^O
Subroutine __ANON__: not called CC=1 SCAR=6.9
39 0 ▶ p => [ 'd', sub { $$ }, ], # pid: $$
Subroutine __ANON__: not called CC=1 SCAR=6.9
40 4 ▶ P => [ 's', sub { (caller(2 + $caller_depth))[0] }, ], # caller_pkg: caller
Subroutine __ANON__: called CC=1 SCAR=0.0
41 0 ▶ r => [ 'd', sub { time - $^T }, ], # runtime: $^T
Subroutine __ANON__: not called CC=1 SCAR=6.9
42 S => [ 's', \&__format_S, ], # caller_sub: caller
43 0 ▶ t => [ 's', sub { scalar localtime }, ],# localtime: scalar localtime
Subroutine __ANON__: not called CC=1 SCAR=6.9
44 0 ▶ T => [ 'd', sub { time }, ], # unix_time: time
Subroutine __ANON__: not called CC=1 SCAR=6.9
45 0 ▶ u => [ 'd', sub { $> }, ], # effective_uid: $>
Subroutine __ANON__: not called CC=1 SCAR=6.9
46 0 ▶ U => [ 'd', sub { $< }, ], # real_uid: $<
Subroutine __ANON__: not called CC=1 SCAR=6.9
47 0 ▶ v => [ 'd', sub { $] }, ], # long_perl_ver: $]
Subroutine __ANON__: not called CC=1 SCAR=6.9
48 0 ▶ V => [ 's', sub { sprintf("%vd", $^V) }, ], # short_perl_ver
Subroutine __ANON__: not called CC=1 SCAR=1.2
49 );
50  
51 1 ▶sub __format_S { my $t = (caller(2 + $caller_depth))[3]; if ( !defined $t || $t eq 'Log::Tiny::AUTOLOAD' ) { $t = 'main'; }; $t; }
Subroutine __format_S: called CC=3 SCAR=12.0
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $t or $t eq "Log::Tiny::AUTOLOAD") 1 0 1
Condition33%1/3
not defined $t or $t eq "Log::Tiny::AUTOLOAD"
l!l&&r!l&&!r
010
MC/DC0%0/2
not defined $t or $t eq "Log::Tiny::AUTOLOAD"
not defined $t $t eq "Log::Tiny::AUTOLOAD"
Truth table33%1/3
not(A) or B
A= not defined $tB= $t eq "Log::Tiny::AUTOLOAD"
ABresult
1X1
011
000
52  
53 # %D{...} -> POSIX::strftime with the brace pattern (ISO-ish default when
54 # no pattern given). The third arg is the per-occurrence brace contents.
55 3 ▶sub __format_D {
Subroutine __format_D: called CC=3 SCAR=11.0
56 3 my ( undef, undef, $pattern ) = @_;
57 3 ▶ $pattern = '%Y-%m-%d %H:%M:%S' unless defined $pattern && length $pattern;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pattern and length $pattern 2 1 3
Condition66%2/3
defined $pattern and length $pattern
!ll&&!rl&&r
201
MC/DC50%1/2
defined $pattern and length $pattern
defined $pattern length $pattern
Truth table66%2/3
A and B
A= defined $patternB= length $pattern
ABresult
0X0
100
111
58 3 return POSIX::strftime( $pattern, localtime );
59 }
60  
61 =head1 SYNOPSIS
62  
63 This module aims to be a light-weight implementation
64 *similar* to L<Log::Log4perl> for logging data to a file.
65  
66 Its use is very straight forward:
67  
68 use Log::Tiny;
69  
70 my $log = Log::Tiny->new( 'myapp.log' ) or
71 die 'Could not log! (' . Log::Tiny->errstr . ')';
72  
73 foreach ( 1 .. 20 ) {
74 $log->DEBUG( "Performing extensive computations on $_" ) if $DEBUG;
75 unless ( extensively_compute( $_ ) ) {
76 $log->WARN(
77 "Investigating error (this may take a while)..."
78 );
79 $log->ERROR( find_error() );
80 save_state();
81 exit 1;
82 } else {
83 $log->INFO( "Everything's A-OK!" );
84 }
85 }
86  
87 =head1 FUNCTIONS
88  
89 =head2 new
90  
91 Create a new Log::Tiny object. The first argument is the log
92 destination and, optionally, a format follows.
93  
94 The destination may be:
95  
96 =over 4
97  
98 =item * a filename, which is opened for append (the common case);
99  
100 =item * an already-open filehandle (glob, glob ref or IO::Handle
101 object), which is used as-is and B<not> closed when the object is
102 destroyed -- handy for logging to C<\*STDERR> or a handle you manage;
103  
104 =item * the string C<"-">, which logs to C<STDOUT>.
105  
106 =back
107  
108 An optional third argument is a hash reference of format specifications
109 that are merged over (and so may extend or override) the defaults for
110 this object only. The format table is snapshotted per-instance, so
111 customising one Log::Tiny object never affects another.
112  
113 =cut
114  
115 24 ▶sub new {
Subroutine new: called CC=8 SCAR=20.9
Pod documented
116 24 my $pkg = shift;
117 24 my $logfile = shift;
118 24 ▶ return _error('No logfile provided') unless defined $logfile && length $logfile;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $logfile and length $logfile 0 24 24
Condition33%1/3
defined $logfile and length $logfile
!ll&&!rl&&r
0024
MC/DC0%0/2
defined $logfile and length $logfile
defined $logfile length $logfile
Truth table33%1/3
A and B
A= defined $logfileB= length $logfile
ABresult
0X0
100
111
119 24 ▶ my $format = shift || '[%t] %f:%p (%c) %m%n';
Condition50%1/2
shift() || '[%t] %f:%p (%c) %m%n'
l!l
240
MC/DC0%0/1
shift() || '[%t] %f:%p (%c) %m%n'
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
120 24 my $custom = shift; # optional hashref of extra/override format specs
121  
122 # snapshot the format table per-instance so customisation does not
123 # leak across objects (the package %formats stays the default template)
124 24 my %fmt = %formats;
125 24 ▶ %fmt = ( %fmt, %$custom ) if ref $custom eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $custom eq "HASH" 2 22 24
126  
127 24 my ( $logfh, $owns_fh );
128 24 ▶ if ( defined Scalar::Util::openhandle($logfile) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined &Scalar::Util::openhandle($logfile)) { } 18 6 24
elsif ($logfile eq '-') { } 1 5 6
129 # caller passed an already-open handle: use it, and don't close it
130 18 $logfh = $logfile;
131 18 $owns_fh = 0;
132 } elsif ( $logfile eq '-' ) {
133 1 $logfh = \*STDOUT;
134 1 $owns_fh = 0;
135 } else {
136 5 ▶ open ( $logfh, '>>', $logfile ) ||
Branch: 1 branch
BranchTrueFalseTotal
open $logfh, ">>", $logfile or return _error("Could not open ${logfile}: $!") 4 1 5
137 return _error( "Could not open $logfile: $!" );
138 4 $owns_fh = 1;
139 }
140 23 $logfh->autoflush(1);
141 23 my $self = bless {
142 format => $format,
143 methods_only => [],
144 logfile => $logfile,
145 logfh => $logfh,
146 owns_fh => $owns_fh,
147 formats => \%fmt,
148 }, $pkg;
149 23 $self->format();
150 23 return $self;
151 }
152  
153 =head2 format
154  
155 You may, at any time, change the format. The log format is
156 similar in style to the sprintf you know and love; and, as
157 a peek inside the source of this module will tell you, sprintf
158 is used internally. However, be advised that these log formats
159 B<are not sprintf>.
160  
161 Interpolated data are specified by an percent sign (C< % >),
162 followed by a character. A literal percent sign can be
163 specified via two in succession ( C< %% > ). You may use any
164 of the formatting attributes as noted in L<perlfunc>, under
165 "sprintf" (C<perldoc -f sprintf>).
166  
167 Internally, the format routine uses a data structure (hash)
168 that can be seen near the beginning of this package. Any
169 unrecognized interpolation variables will be returned
170 literally. This means that, assuming $format{d} does not
171 exist, "%d" in your format will result in "%d" being outputted
172 to the log file. No interpolation will occur.
173  
174 You may, of course, decide to modify the format data structure.
175 I have done my best to ensure a wide range of variables for your
176 usage, however. They are (currently) as follows:
177  
178 c => category => The method called (see below for more info)
179 C => lcategory => lowercase category
180 D => date (strftime)=> %D{...} formats now() with the brace strftime
181 pattern (default "%Y-%m-%d %H:%M:%S")
182 f => program_file => Value of $0
183 F => caller_file => Calling file
184 g => gmtime => Output of scalar L<gmtime> (localized date string)
185 L => caller_line => Calling line
186 m => message => Message sent to the log method
187 n => newline => Value of $/
188 o => osname => Value of $^O
189 p => pid => Value of $$
190 P => caller_pkg => Calling package
191 r => runtime => Seconds the current process has been running for
192 S => caller_sub => Calling subroutine
193 t => localtime => Output of scalar L<localtime> (localized date
194 string)
195 T => unix_time => Time since epoch (L<time>)
196 u => effective_uid => Value of $>
197 U => real_uid => Value of $<
198 v => long_perl_ver => Value of $] (5.008008)
199 V => short_perl_ver => A "short" string for the version ("5.8.8")
200  
201 See L<perlvar> for information on the used global variables, and
202 L<perlfunc> (under "caller") or C<perldoc -f caller> for information
203 on the "calling" variables. Oh, and make sure you add %n if you want
204 newlines.
205  
206 =cut
207  
208 23 ▶sub format {
Subroutine format: called CC=2 SCAR=7.1
Pod documented
209 23 my $self = shift;
210 23 ▶ if ( $_[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]) 0 23 23
211 0 $self->{format} = shift;
212 }
213 23 $self->{args} = [];
214 # Compile the log format into an sprintf template. Every %-sequence is
215 # rewritten here: known codes become real conversions (value captured
216 # in {args}); %% and any unrecognised code (e.g. %d) are escaped to a
217 # literal so the final sprintf in AUTOLOAD can never consume an argument
218 # for them. Matching any trailing char -- not just known codes -- is what
219 # makes unknown codes come out literally, as the POD promises.
220 $self->{format} =~
221 23 s/%(-?\d*(?:\.\d+)?)(?:([A-Za-z])\{([^}]*)\}|(.))/_replace($self, $1, $2, $3, $4)/gexs;
222 # thanks, mschilli
223 23 return $self->{format};
224 }
225  
226 48 ▶sub _replace {
Subroutine _replace: called CC=4 SCAR=13.9
227 48 my ( $self, $num, $braceop, $arg, $op ) = @_;
228 48 ▶ $op = $braceop if defined $braceop; # %X{...} form
Branch: 1 branch
BranchTrueFalseTotal
if defined $braceop 1 47 48
229 48 ▶ return '%%' if $op eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "%" 1 47 48
230 47 ▶ return "%%$num$op" unless defined $self->{formats}{$op};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"formats"}{$op} 2 45 47
231 45 push @{ $self->{args} }, [ $op, $arg ];
232 45 return "%$num" . $self->{formats}{$op}->[ 0 ];
233 }
234  
235 =head2 WHATEVER_YOU_WANT (log a message)
236  
237 This method is whatever you want it to be. Any method called
238 on a Log::Tiny object that is not reserved will be considered
239 an attempt to log in the category named the same as the method
240 that was called. Currently, only in-use methods are reserved;
241 However, to account for expansion, please only use uppercase
242 categories. See formats above for information on customizing
243 the log messages.
244  
245 =cut
246  
247 50 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=5 SCAR=16.1
248 50 my $self = shift;
249 50 my $method = $AUTOLOAD;
250 50 $method =~ s/.*:://;
251 50 ▶ return _error( "Log routine ($method) is not a class method" )
Branch: 1 branch
BranchTrueFalseTotal
unless defined ref $self 0 50 50
252 unless defined ref $self;
253 # skip anything filtered out by log_only() / min_level()
254 50 ▶ return 0 unless $self->would_log( $method );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->would_log($method) 6 44 50
255 44 my $tmp = '';
256 44 foreach my $msg ( @_ ) {
257 # lazy messages: a coderef is only invoked once we know the
258 # message will actually be logged (we are past the threshold).
259 44 ▶ $msg = $msg->() if ref $msg eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $msg eq "CODE" 1 43 44
260 44 $tmp .= sprintf( $self->{format}, $self->_mk_args( $method, $msg ) );
261 }
262 44 return print {$self->{logfh}} $tmp;
263 }
264  
265 =head2 would_log
266  
267 Returns true if a message logged under the given category would actually
268 be emitted (i.e. it passes both L</log_only> and L</min_level>). Use it
269 to guard expensive work:
270  
271 $log->DEBUG( sub { expensive_dump() } ); # or:
272 $log->DEBUG( pricey() ) if $log->would_log('DEBUG');
273  
274 Passing a code reference as the message (above) is usually simpler: the
275 sub is only called when the message would be logged.
276  
277 =cut
278  
279 56 ▶sub would_log {
Subroutine would_log: called CC=8 SCAR=20.8
Pod documented
280 56 my ( $self, $category ) = @_;
281 56 ▶ $category = '' unless defined $category;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $category 0 56 56
282 56 ▶ if ( @{ $self->{methods_only} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"methods_only"};}) 5 51 56
283 5 my $in = grep { uc $category eq uc $_ } @{ $self->{methods_only} };
284 5 ▶ return !!0 unless $in;
Branch: 1 branch
BranchTrueFalseTotal
unless $in 2 3 5
285 }
286 54 ▶ if ( defined $self->{min_level} && $self->{level_map} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"min_level"} and $self->{"level_map"}) 15 39 54
Condition66%2/3
defined $self->{"min_level"} and $self->{"level_map"}
!ll&&!rl&&r
39015
MC/DC50%1/2
defined $self->{"min_level"} and $self->{"level_map"}
defined $self->{"min_level"} $self->{"level_map"}
Truth table66%2/3
A and B
A= defined $self->{"min_level"}B= $self->{"level_map"}
ABresult
0X0
100
111
287 15 my $lvl = $self->{level_map}{ uc $category };
288 15 ▶ return !!0 if defined $lvl && $lvl < $self->{min_level};
Branch: 1 branch
BranchTrueFalseTotal
if defined $lvl and $lvl < $self->{"min_level"} 6 9 15
Condition100%3/3
defined $lvl and $lvl < $self->{"min_level"}
!ll&&!rl&&r
276
MC/DC100%2/2
defined $lvl and $lvl < $self->{"min_level"}
defined $lvl $lvl < $self->{"min_level"}
Truth table100%3/3
A and B
A= defined $lvlB= $lvl < $self->{"min_level"}
ABresult
0X0
100
111
289 }
290 48 return !!1;
291 }
292  
293 44 ▶sub _mk_args {
Subroutine _mk_args: called CC=2 SCAR=7.0
294 44 my $self = shift;
295 44 my ( $method, $msg ) = @_;
296 44 ▶ $msg = '' unless defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $msg 0 44 44
297 # compute each captured code in format order; $_->[1] is the optional
298 # brace argument (e.g. the strftime pattern for %D{...}).
299 79 return map { $self->{formats}{ $_->[0] }->[1]->( $method, $msg, $_->[1] ) }
300 44 @{ $self->{args} };
301 }
302  
303 21 ▶sub DESTROY {
Subroutine DESTROY: called CC=3 SCAR=11.1
304 21 my $self = shift;
305 # only close handles we opened ourselves; leave caller-supplied
306 # handles (STDERR, STDOUT, etc.) alone
307 21 ▶ return unless $self->{owns_fh};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"owns_fh"} 17 4 21
308 4 ▶ close $self->{logfh} or warn "Couldn't close log file: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $self->{"logfh"} or warn "Couldn't close log file: $!" 4 0 4
309 }
310  
311 =head2 errstr
312  
313 Called as a class method, C< Log::Tiny->errstr > reveals the
314 error that Log::Tiny encountered in creation or invocation.
315  
316 =cut
317  
318 3 ▶sub errstr { $errstr; }
Subroutine errstr: called CC=1 SCAR=0.0
Pod documented
319 2 ▶sub _error { $errstr = shift; undef; }
Subroutine _error: called CC=1 SCAR=0.0
320  
321 =head2 Caller depth (C<$Log::Tiny::caller_depth>)
322  
323 The C<%F>, C<%L>, C<%P> and C<%S> formats report the file, line,
324 package and subroutine of the code that called the log method. If you
325 wrap your logging in a helper of your own, that helper becomes the
326 apparent caller. As with L<Log::Log4perl>, localise
327 C<$Log::Tiny::caller_depth> to skip the extra frame(s):
328  
329 sub my_log {
330 local $Log::Tiny::caller_depth = 1;
331 $log->INFO( @_ );
332 }
333  
334 =head2 log_only
335  
336 Log only the given categories
337  
338 =cut
339  
340 2 ▶sub log_only {
Subroutine log_only: called CC=1 SCAR=0.0
Pod documented
341 2 my $self = shift;
342 2 $self->{methods_only} = \@_;
343 }
344  
345 =head2 levels
346  
347 Define an ordered list of severities, least to most severe:
348  
349 $log->levels( [qw(DEBUG INFO WARN ERROR FATAL)] );
350  
351 Level names are compared case-insensitively. On their own, levels do
352 nothing; combine with L</min_level> to filter. This is independent of
353 L</log_only> (which whitelists exact categories).
354  
355 =cut
356  
357 4 ▶sub levels {
Subroutine levels: called CC=3 SCAR=11.0
Pod documented
358 4 my $self = shift;
359 4 my $list = shift;
360 4 ▶ return _error('levels() expects an array reference')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $list eq "ARRAY" 0 4 4
361 unless ref $list eq 'ARRAY';
362 4 my %map;
363 4 my $i = 0;
364 4 $map{ uc $_ } = $i++ for @$list;
365 4 $self->{level_map} = \%map;
366 4 return $self->{level_map};
367 }
368  
369 =head2 min_level
370  
371 Get or set the minimum severity that will be logged. Categories at or
372 above the threshold are logged; those below it are dropped; categories
373 not present in the L</levels> list are always logged.
374  
375 $log->min_level('WARN'); # set
376 my $current = $log->min_level; # get (undef if unset)
377  
378 Requires L</levels> to have been called first. Returns C<undef> (and
379 sets L</errstr>) for an unknown level name.
380  
381 =cut
382  
383 7 ▶sub min_level {
Subroutine min_level: called CC=4 SCAR=13.9
Pod documented
384 7 my $self = shift;
385 7 ▶ return $self->{min_level_name} unless @_; # getter
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 1 6 7
386 6 my $name = uc shift;
387 my $map = $self->{level_map}
388 6 ▶ or return _error('Call levels() before min_level()');
Branch: 1 branch
BranchTrueFalseTotal
my $map = $self->{"level_map"} or return _error("Call levels() before min_level()") 6 0 6
389 6 ▶ return _error("Unknown level '$name'") unless exists $map->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $map->{$name} 1 5 6
390 5 $self->{min_level} = $map->{$name};
391 5 $self->{min_level_name} = $name;
392 5 return $name;
393 }
394  
395 =head2 LOGWARN / LOGDIE / LOGCARP / LOGCLUCK / LOGCROAK / LOGCONFESS
396  
397 Log-and-C<warn>/C<die> convenience methods, modelled on
398 L<Log::Log4perl>. Each logs the message under a category
399 (C<WARN> for the C<warn>/C<carp>/C<cluck> variants, C<FATAL> for the
400 C<die>/C<croak>/C<confess> variants) and then raises it:
401  
402 $log->LOGWARN("disk getting full"); # logs (WARN) then warn()s
403 $log->LOGDIE("out of disk"); # logs (FATAL) then die()s
404 $log->LOGCROAK("bad args"); # logs then Carp::croak()s
405  
406 The C<CARP>/C<CLUCK>/C<CROAK>/C<CONFESS> variants delegate to L<Carp>.
407 These names are reserved and cannot be used as ordinary log categories.
408  
409 =cut
410  
411 # category logged under, and the action to raise afterwards
412 my %LOG_AND = (
413 1 ▶ LOGWARN => [ 'WARN', sub { warn @_ } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
414 1 ▶ LOGDIE => [ 'FATAL', sub { die @_ } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
415 0 ▶ LOGCARP => [ 'WARN', sub { Carp::carp @_ } ],
Subroutine __ANON__: not called CC=1 SCAR=6.9
416 0 ▶ LOGCLUCK => [ 'WARN', sub { Carp::cluck @_ } ],
Subroutine __ANON__: not called CC=1 SCAR=6.9
417 1 ▶ LOGCROAK => [ 'FATAL', sub { Carp::croak @_ } ],
Subroutine __ANON__: called CC=1 SCAR=0.0
418 0 ▶ LOGCONFESS => [ 'FATAL', sub { Carp::confess @_ } ],
Subroutine __ANON__: not called CC=1 SCAR=1.2
419 );
420  
421 {
422 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
423 16 for my $name ( keys %LOG_AND ) {
424 96 my ( $category, $action ) = @{ $LOG_AND{$name} };
425 96 ▶ *{$name} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
426 3 my $self = shift;
427 3 $self->$category( @_ );
428 3 $action->( @_ );
429 96 };
430 }
431 }
432  
433 =head1 EASY MODE
434  
435 Import the C<:easy> tag for a functional interface that logs through a
436 single process-wide logger, so short scripts need not carry an object:
437  
438 use Log::Tiny ':easy';
439 INFO("started");
440 ERROR("boom");
441 LOGDIE("fatal");
442  
443 The functions exported are C<TRACE>, C<DEBUG>, C<INFO>, C<WARN>,
444 C<ERROR>, C<FATAL> and the C<LOG*> family above. The default logger
445 writes to C<STDERR> with the format C<[%D] [%c] %m%n>; call
446 L</easy_init> to change the destination, format or level.
447  
448 =head2 easy_init
449  
450 Configure (or reconfigure) the C<:easy> logger. Accepts either a
451 positional C<($destination, $format)> pair or a hash reference:
452  
453 Log::Tiny->easy_init('/var/log/app.log');
454 Log::Tiny->easy_init(\*STDOUT, '%D %m%n');
455 Log::Tiny->easy_init({ file => 'app.log', format => '%m%n',
456 level => 'INFO' });
457  
458 The C<level> key (hash form) installs the standard
459 C<TRACE E<lt> DEBUG E<lt> INFO E<lt> WARN E<lt> ERROR E<lt> FATAL> order
460 and sets it as the L</min_level> threshold. Returns the logger.
461  
462 =cut
463  
464 16 our @EASY_LEVELS = qw( TRACE DEBUG INFO WARN ERROR FATAL );
465  
466 3 ▶sub easy_init {
Subroutine easy_init: called CC=11 SCAR=24.6
Pod documented
467 3 my $class = shift;
468 3 my ( $dest, $format, $level );
469 3 ▶ if ( @_ == 1 && ref $_[0] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0] eq 'HASH') { } 1 2 3
Condition66%2/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
201
MC/DC50%1/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
470 1 my $o = $_[0];
471 $dest = exists $o->{file} ? $o->{file}
472 : exists $o->{fh} ? $o->{fh}
473 1 ▶ : \*STDERR;
Branch: 2 branches
BranchTrueFalseTotal
exists $o->{'file'} ? : 0 1 1
exists $o->{'fh'} ? : 1 0 1
474 1 ▶ $format = $o->{format} || $o->{layout};
Condition33%1/3
$o->{'format'} || $o->{'layout'}
l!l&&r!l&&!r
100
MC/DC0%0/2
$o->{'format'} || $o->{'layout'}
$o->{'format'} $o->{'layout'}
Truth table33%1/3
A || B
A= $o->{'format'}B= $o->{'layout'}
ABresult
1X1
011
000
475 1 $level = $o->{level};
476 }
477 else {
478 2 ( $dest, $format ) = @_;
479 2 ▶ $dest = \*STDERR unless defined $dest;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dest 1 1 2
480 }
481 3 ▶ $format = '[%D] [%c] %m%n' unless defined $format && length $format;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $format and length $format 1 2 3
Condition66%2/3
defined $format and length $format
!ll&&!rl&&r
102
MC/DC50%1/2
defined $format and length $format
defined $format length $format
Truth table66%2/3
A and B
A= defined $formatB= length $format
ABresult
0X0
100
111
482 3 ▶ $easy = $class->new( $dest, $format )
Branch: 1 branch
BranchTrueFalseTotal
$Log::Tiny::easy = $class->new($dest, $format) or Carp::croak('Log::Tiny easy_init failed: ' . $class->errstr) 3 0 3
483 or Carp::croak( "Log::Tiny easy_init failed: " . $class->errstr );
484 3 ▶ if ( defined $level ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $level) 1 2 3
485 1 $easy->levels( \@EASY_LEVELS );
486 1 $easy->min_level( $level );
487 }
488 3 return $easy;
489 }
490  
491 # lazily build the default :easy logger (STDERR) on first use
492 4 ▶sub _easy {
Subroutine _easy: called CC=2 SCAR=6.9
493 4 ▶ $easy = __PACKAGE__->easy_init() unless defined $easy;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Log::Tiny::easy 1 3 4
494 4 return $easy;
495 }
496  
497 16 my %EASY_FN;
498 {
499 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
500 16 for my $lvl ( @EASY_LEVELS ) {
501 4 ▶ $EASY_FN{$lvl} = sub { _easy()->$lvl(@_) };
Subroutine __ANON__: called CC=1 SCAR=0.0
502 }
503 16 for my $name ( keys %LOG_AND ) {
504 0 ▶ $EASY_FN{$name} = sub { _easy()->$name(@_) };
Subroutine __ANON__: not called CC=1 SCAR=1.2
505 }
506 }
507  
508 16 ▶sub import {
Subroutine import: called CC=4 SCAR=13.9
509 16 my $class = shift;
510 16 my $caller = caller;
511 16 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
512 16 for my $tag ( @_ ) {
513 1 ▶ next unless $tag eq ':easy';
Branch: 1 branch
BranchTrueFalseTotal
unless $tag eq ":easy" 0 1 1
514 1 *{"${caller}::$_"} = $EASY_FN{$_} for keys %EASY_FN;
515 }
516 }
517  
518 =head1 AUTHOR
519  
520 Jordan M. Adler, C<< <jmadler at cpan.org> >>
521  
522 =head1 BUGS
523  
524 Please report any bugs or feature requests to
525 C<bug-log-tiny at rt.cpan.org>, or through the web interface at
526 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Log-Tiny>.
527 I will be notified, and then you'll automatically be notified of progress on
528 your bug as I make changes.
529  
530 =head1 SUPPORT
531  
532 You can find documentation for this module with the perldoc command.
533  
534 perldoc Log::Tiny
535  
536 You can also look for information at:
537  
538 =over 4
539  
540 =item * AnnoCPAN: Annotated CPAN documentation
541  
542 L<http://annocpan.org/dist/Log-Tiny>
543  
544 =item * CPAN Ratings
545  
546 L<http://cpanratings.perl.org/d/Log-Tiny>
547  
548 =item * RT: CPAN's request tracker
549  
550 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Log-Tiny>
551  
552 =item * Search CPAN
553  
554 L<http://search.cpan.org/dist/Log-Tiny>
555  
556 =item * GitHub
557  
558 L<https://github.com/jmadler/p5-log-tiny>
559  
560 =back
561  
562 =head1 ACKNOWLEDGEMENTS
563  
564 Much thanks to Michael Schilli C<CPAN:mschilli> for his great work on
565 Log::Log4perl, of which this module's formatting concept is largely based upon.
566  
567 =head1 COPYRIGHT & LICENSE
568  
569 Copyright 2007-2022 Jordan M. Adler, all rights reserved.
570  
571 This program is free software; you can redistribute it and/or modify it
572 under the same terms as Perl itself.
573  
574 =cut
575  
576 16 1; # End of Log::Tiny
↑ Summary example.pl »