Synchronize/Logger.pm

filter: Statementstmt 81.0% 81 / 100 Branchbran 71.7% 33 / 46 Conditioncond 75.0% 15 / 20 MC/DCmcdc 61.5% 8 / 13 Subroutinesub 73.6% 14 / 19 Podpod 72.7% 8 / 11 totaltotal 76.0% 159 / 209 CC 33 SCAR 21.8
CC
33
Cov
78%
log_message
16.0
set_as_default
12.0
set_printer
11.7
CRAP 8.9
« Synchronize/ProgressBar.pm ↑ Summary Synchronize/Timestamp.pm »
1 package Image::Synchronize::Logger;
2
3 3 ▶use v5.10.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
4
5 # I would have liked to use Log::Contextual, but I can't figure out
6 # how to make it play nice with Term::ProgressBar::Simple, and how to
7 # select the desired logging level based on a command-line option.
8
9 =head1 NAME
10
11 Image::Synchronize::Logger - a message logger for Imsync
12
13 =head1 SYNOPSIS
14
15 # arrange to print to STDERR at level 0 and up
16 $l1 = Image::Synchronize::Logger->new;
17
18 $l1->log_message('unconditional', ' multiple arguments');
19 # prints 'unconditional multiple arguments' to STDERR
20
21 $l1->log_message($level, 'this too?');
22 # prints 'this too?' to STDERR if $level is a number >= 0
23
24 # Image::Synchronize::Logger->new() is equivalent to
25 $l1 = Image::Synchronize::Logger->new({ name => '',
26 min_level => 0,
27 action => sub { print STDERR, @_ } });
28
29 # arrange to print through the code reference at level 2 and up
30 $l2 = Image::Synchronize::Logger->new({ name => 'myprinter',
31 min_level => 2,
32 action => sub { print 'Hey! ', @_; } });
33
34 $l2->log_message(1, 'level 1');
35 # not printed because verbosity level 1 is less than the minimum
36 # level (2) defined for the single backend printer of the logger
37
38 $l2->log_message(2, 'level 2');
39 # prints 'Hey! level 2' to STDOUT
40
41 # arrange to also print to a file at level 1 and up
42 open $ofh, '>>', 'mylog.log';
43 $l2->set_printer({ name => 'tofile',
44 min_level => 1,
45 action => sub { print $ofh @_ } });
46
47 $l2->log_message(1, 'level 1');
48 # prints 'level 1' to the file
49
50 $l2->log_message(2, 'level 2');
51 # prints 'level 2' to the file, and 'Hey! level 2' to STDOUT
52
53 # change 'Hey!' to 'Wow!' for printing to STDOUT
54 $l2->set_printer({ name => 'myprinter',
55 min_level => 2,
56 action => sub { print 'Wow! ', @_; } });
57
58 $l2->log_message(2, 'level 2');
59 # prints 'level 2' to the file, and 'Wow! level 2' to STDOUT
60
61 # remove myprinter
62 $l2->clear_printer('myprinter');
63
64 $l2->log_message(2, 'level 2');
65 # prints 'level 2' to the file
66
67 # install as default logger
68 $l2->set_as_default;
69
70 # access the default logger
71 $l = default_logger();
72
73 # now these are equivalent:
74 $l2->log_message(@args);
75 log_message(@args);
76
77 # the arguments can be code references, which get evaluated with no
78 # arguments.
79 $l2->log_message(2, sub { 'This is some text' });
80 # prints 'This is some text' to the file
81
82 # arguments that are array references get the referenced array
83 # interpolated. These are equivalent:
84 $l->log_message(1, 'this', [' is', ' text']);
85 $l->log_message(1, 'this', ' is', ' text');
86
87 # log a message when the message verbosity is at least 2 or if
88 # option 'X' is equal to 'foo'
89 $l->set_printer({ name => '',
90 min_level => 2,
91 action => sub { print @_; } });
92 $l->set_printer_condition('', 'foo condition',
93 sub { $_->{X} eq 'foo' });
94 $l->log_message(1, @args); # not printed, verbosity too low
95 $l->log_message(1, { X => 'bar' }, @args); # not printed
96 $l->log_message(1, { X => 'foo' }, @args); # args get printed
97
98 =head1 SUBROUTINES/METHODS
99
100 =over
101
102 =cut
103
104 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
105 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
106
107 3 ▶use parent 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
108 3 our @EXPORT_OK = qw(
109 default_logger
110 log_error
111 log_message
112 log_warn
113 set_printer
114 );
115
116 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
117 3 ▶use Scalar::Util qw(blessed looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
118
119 0 ▶my $default_printer = sub { print STDERR @_ };
Subroutine __ANON__: not called CC=1 SCAR=1.2
120
121 =item new
122
123 $l = Image::Synchronize::Logger->new($name, $min_level, $coderef);
124 $l = Image::Synchronize::Logger->new({ name => $name,
125 min_level => $min_level,
126 bitflags => $bitflags,
127 action => $coderef });
128 $l = Image::Synchronize::Logger->new;
129 # equivalent to ->new({ name => '',
130 min_level => 0,
131 action => sub { print STDERR @_ } });
132
133 Constructs a new instance of the class for logging messages to one or
134 more back-end printers, based on a minimum verbosity level and/or bit
135 flags.
136
137 C<$name> is the name of the back-end printer, through which it can be
138 queried or modified later.
139
140 C<$min_level> is the minimum verbosity level of the back-end printer.
141 A logged message gets printed through the back-end printer if its
142 verbosity level is at least as great as C<$min_level>.
143
144 C<$bitflags> is a number that identifies which bits of the verbosity
145 level are bit flags. If a message is logged at a verbosity level that
146 includes any of those bits, then that message gets logged through the
147 current back-end printer.
148
149 C<$coderef> is a code reference that says how the message should be
150 printed. The messages to be logged show up in C<@_> inside that code
151 reference.
152
153 =cut
154
155 2 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
156 2 my $class = shift;
157 2 my $self = bless {}, $class;
158 2 return $self->set_printer(@_)->ensure_printer_;
159 }
160
161 # $logger->ensure_printer_
162 #
163 # Ensure that the logger has at least one back-end printer. If it
164 # doesn't have a back-end printer yet, then install a default printer
165 # (with name '') that prints to STDERR.
166 #
167 # Returns the logger object.
168 3 ▶sub ensure_printer_ {
Subroutine ensure_printer_: called CC=2 SCAR=7.4
Pod undocumented
169 3 my ($self) = @_;
170 3 ▶ unless ( keys %{ $self->{printers} } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (keys %{$$self{"printers"};}) 0 3 3
171 0 $self->{printers}->{''} = {
172 min_level => 0,
173 action => $default_printer
174 };
175 }
176 3 return $self;
177 }
178
179 29 ▶sub get_logger_ {
Subroutine get_logger_: called CC=3 SCAR=11.0
Pod undocumented
180 29 ▶ if ( blessed( $_[0]->[0] ) && $_[0]->[0]->isa('Image::Synchronize::Logger') )
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($_[0][0]) and $_[0][0]->isa('Image::Synchronize::Logger')) { } 27 2 29
Condition66%2/3
builtin::blessed($_[0][0]) and $_[0][0]->isa("Image::Synchronize::Logger")
!ll&&!rl&&r
2027
MC/DC50%1/2
builtin::blessed($_[0][0]) and $_[0][0]->isa("Image::Synchronize::Logger")
builtin::blessed($_[0][0]) $_[0][0]->isa("Image::Synchronize::Logger")
Truth table66%2/3
A and B
A= builtin::blessed($_[0][0])B= $_[0][0]->isa("Image::Synchronize::Logger")
ABresult
0X0
100
111
181 {
182 27 shift @{ $_[0] };
183 }
184 else {
185 2 default_logger();
186 }
187 }
188
189 =item clear_printer
190
191 $l->clear_printer($name);
192 clear_printer($name); # default logger
193
194 Removes the named back-end printer from the logger. If no printer by
195 that name is known to the logger, then does nothing. If removal of
196 the back-end printer leaves the logger without any back-end printers,
197 then installs a default back-end printer (with name C<''>) that prints
198 to STDERR.
199
200 Returns the logger object.
201
202 =cut
203
204 1 ▶sub clear_printer {
Subroutine clear_printer: called CC=1 SCAR=0.0
Pod documented
205 1 my $logger = get_logger_( \@_ );
206 1 my ($name) = @_;
207 1 delete $logger->{printers}->{$name};
208 1 $logger->ensure_printer_;
209 1 return $logger;
210 }
211
212 =item set_printer_condition
213
214 $l->set_printer_condition($printer_name, $condition_name, $code_ref);
215
216 Adds the C<$code_ref> as a printer condition with name
217 C<$condition_name> to the back-end printer with name C<$printer_name>.
218
219 =cut
220
221 1 ▶sub set_printer_condition {
Subroutine set_printer_condition: called CC=4 SCAR=17.3
Pod documented
222 1 my $logger = get_logger_( \@_ );
223 1 my ( $printer_name, $condition_name, $code_ref ) = @_;
224 croak "Back-end printer '$printer_name' is not defined for the logger.\n"
225 1 ▶ unless exists $logger->{printers}->{$printer_name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $logger->{"printers"}{$printer_name} 0 1 1
226 1 ▶ if ( defined $code_ref ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $code_ref) { } 1 0 1
227 1 $logger->{conditions}->{$condition_name} = $code_ref;
228 }
229 else {
230 0 delete $logger->{conditions}->{$condition_name};
231 0 ▶ delete $logger->{conditions} unless keys %{ $logger->{conditions} };
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$$logger{"conditions"};} 0 0 0
232 }
233 1 $logger;
234 }
235
236 =item default_logger
237
238 $default_logger = default_logger();
239
240 Returns the default logger, which is an instance of C<Image::Synchronize::Logger>.
241
242 =cut
243
244 3 my $default_logger;
245
246 2 ▶sub default_logger {
Subroutine default_logger: called CC=2 SCAR=7.1
Pod documented
247 2 ▶ $default_logger //= Image::Synchronize::Logger->new;
Condition66%2/3
$default_logger //= "Image::Synchronize::Logger"->new
l!l&&r!l&&!r
110
MC/DC0%0/2
$default_logger //= "Image::Synchronize::Logger"->new
$default_logger "Image::Synchronize::Logger"->new
Truth table66%2/3
A //= B
A= $default_loggerB= "Image::Synchronize::Logger"->new
ABresult
1X1
011
000
248 2 return $default_logger;
249 }
250
251 =item log
252
253 $l->log_message($level, { %options }, @arguments);
254 # $level and %options are optional
255
256 # or use the default logger
257 log_message($level, { %options }, @arguments);
258
259 Log a message through all applicable back-end printers of the logger.
260
261 If the first specified argument is a scalar number, then it represents
262 the verbosity level of the message. The verbosity level defaults to
263 0.
264
265 If, after removing the verbosity level if any, the first specified
266 argument is a hash reference, then it represents information to pass
267 to the special condition evaluator of the printer, if defined.
268
269 The remaining arguments represent values to print. If any of them are
270 code references, then they are evaluated before printing, with no
271 arguments. Evaluation is done only if the message gets printed
272 through at least one of the back-end printers, so if any of the values
273 to be printed are expensive to evaluate, then wrap them in an
274 anonymous sub to prevent them from being evaluated if they aren't
275 needed.
276
277 Returns the logger object.
278
279 The message gets printed through the back-end printer if C<$level>
280 matches the printer's maximum verbosity level or bit flag or if any of
281 the printer's special conditions are met.
282
283 The printer's maximum verbosity level (if specified) is matched if
284 C<$level> is less than or equal to that maximum verbosity level.
285
286 The printer's bit flag (if specified) is matched if at least one of
287 the bits in the printer's bit flag are set in C<$level>.
288
289 If the printer has one or more special conditions defined
290 (L<set_printer_condition>), then the code reference for each of those
291 conditions gets evaluated with C<{%options}> as argument, and the
292 condition is met if it evaluates to a true value.
293
294 =cut
295
296 20 ▶sub log_message {
Subroutine log_message: called CC=16 SCAR=27.7
Pod undocumented
297 20 my $logger = get_logger_( \@_ );
298 20 ▶ my $level = shift if looks_like_number( $_[0] );
Branch: 1 branch
BranchTrueFalseTotal
if &looks_like_number($_[0]) 16 4 20
299 20 ▶ my $options_href = shift if ref $_[0] eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] eq "HASH" 1 19 20
300 20 my @args = @_;
301 20 my $was_evaluated;
302 20 foreach my $name ( sort keys %{ $logger->{printers} } ) {
303 38 my $printer = $logger->{printers}->{$name};
304 38 my $do_print = 1;
305 38 ▶ if ( defined $level ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $level) 31 7 38
306 31 my $printer_bitflags = $printer->{bitflags};
307 31 ▶ $do_print = 0
Branch: 1 branch
BranchTrueFalseTotal
if defined $printer_bitflags and ($level & $printer_bitflags) == 0 8 23 31
Condition100%3/3
defined $printer_bitflags and ($level & $printer_bitflags) == 0
!ll&&!rl&&r
1948
MC/DC100%2/2
defined $printer_bitflags and ($level & $printer_bitflags) == 0
defined $printer_bitflags ($level & $printer_bitflags) == 0
Truth table100%3/3
A and B
A= defined $printer_bitflagsB= ($level & $printer_bitflags) == 0
ABresult
0X0
100
111
308 if ( defined($printer_bitflags)
309 && ( $level & $printer_bitflags ) == 0 );
310 31 my $printer_level = $printer->{min_level};
311 31 ▶ $do_print = 0
Branch: 1 branch
BranchTrueFalseTotal
if defined $printer_level and $level < $printer_level 5 26 31
Condition100%3/3
defined $printer_level and $level < $printer_level
!ll&&!rl&&r
15115
MC/DC100%2/2
defined $printer_level and $level < $printer_level
defined $printer_level $level < $printer_level
Truth table100%3/3
A and B
A= defined $printer_levelB= $level < $printer_level
ABresult
0X0
100
111
312 if ( defined $printer_level && $level < $printer_level );
313 }
314 38 ▶ if ( not($do_print) && exists $logger->{conditions} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $do_print and exists $logger->{"conditions"}) 4 34 38
Condition100%3/3
not $do_print and exists $logger->{"conditions"}
!ll&&!rl&&r
2594
MC/DC100%2/2
not $do_print and exists $logger->{"conditions"}
not $do_print exists $logger->{"conditions"}
Truth table100%3/3
not(A) and B
A= not $do_printB= exists $logger->{"conditions"}
ABresult
0X0
100
111
315 4 foreach my $condition_name ( sort keys %{ $logger->{conditions} } ) {
316 4 local $_ = $options_href;
317 $do_print = 1, last
318 4 ▶ if $logger->{conditions}->{$condition_name}->($_);
Branch: 1 branch
BranchTrueFalseTotal
if $logger->{"conditions"}{$condition_name}->($_) 2 2 4
319 }
320 }
321 38 ▶ if ($do_print) {
Branch: 1 branch
BranchTrueFalseTotal
if ($do_print) 27 11 38
322 27 ▶ unless ($was_evaluated) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($was_evaluated) 17 10 27
323 17 ▶ @args = map { ref eq 'CODE' ? $_->() : $_ } @args;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'CODE' ? : 0 17 17
324 17 $was_evaluated = 1;
325 }
326 27 $printer->{action}->(@args);
327 }
328 }
329 20 return $logger;
330 }
331
332 =item log_error
333
334 $l->log_error(@messages);
335 log_error(@messages);
336
337 Logs the C<@messages> (at verbosity levels 0 and up) prefixed by
338 C<'ERROR: '>.
339
340 =cut
341
342 0 ▶sub log_error {
Subroutine log_error: not called CC=1 SCAR=6.9
Pod documented
343 0 my $logger = get_logger_( \@_ );
344 0 return $logger->log_message( 'ERROR: ', @_ );
345 }
346
347 =item log_warn
348
349 $l->log_warn(@messages);
350 log_warn(@messages);
351
352 Logs the C<@messages> (at verbosity levels 0 and up) prefixed by
353 C<'WARNING: '>.
354
355 =cut
356
357 0 ▶sub log_warn {
Subroutine log_warn: not called CC=1 SCAR=6.9
Pod documented
358 0 my $logger = get_logger_( \@_ );
359 0 return $logger->log_message( 'WARNING: ', @_ );
360 }
361
362 =item set_as_default
363
364 $l->set_as_default;
365
366 Installs C<$l> (an Image::Synchronize::Logger) as the default logger, to be
367 returned by L<default_logger()>.
368
369 Returns the logger object.
370
371 =cut
372
373 0 ▶sub set_as_default {
Subroutine set_as_default: not called CC=3 SCAR=24.8
Pod documented
374 0 my ($self) = @_;
375 0 ▶ if ( blessed($self) && $self->isa('Image::Synchronize::Logger') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($self) and $self->isa('Image::Synchronize::Logger')) { } 0 0 0
Condition0%0/3
builtin::blessed($self) and $self->isa("Image::Synchronize::Logger")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($self) and $self->isa("Image::Synchronize::Logger")
builtin::blessed($self) $self->isa("Image::Synchronize::Logger")
Truth table0%0/3
A and B
A= builtin::blessed($self)B= $self->isa("Image::Synchronize::Logger")
ABresult
0X0
100
111
376 0 $default_logger = $self;
377 }
378 else {
379 0 croak "Expected Image::Synchronize::Logger or descendant\n";
380 }
381 0 return $self;
382 }
383
384 =item set_printer
385
386 # with a logger object
387 $l->set_printer($name, $level, $coderef);
388 $l->set_printer({ name => $name,
389 min_level => $level,
390 bitflags => $flags,
391 action => $coderef });
392 $l->set_printer;
393 # equivalent to ->set_printer('', 0, sub { print STDERR @_ })
394
395 # or the same with the default logger
396 set_printer(...);
397
398 Sets a back-end printer of logger C<$l>, or of the default logger,
399 replacing any previous back-end printer with the same name.
400
401 See L<new> for details of the arguments.
402
403 Returns the object.
404
405 =cut
406
407 7 ▶sub set_printer {
Subroutine set_printer: called CC=9 SCAR=24.6
Pod documented
408 7 my $logger = get_logger_( \@_ );
409 7 my ( $name, $level, $bitflags, $code );
410 7 ▶ if ( scalar(@_) == 1 ) { # expect { ... }
Branch: 3 branches
BranchTrueFalseTotal
if (scalar @_ == 1) { } 6 1 7
elsif (scalar @_ == 0) { } 1 0 1
elsif (scalar @_ != 3) { } 0 0 0
411 6 ▶ if ( ref $_[0] eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH') { } 6 0 6
412 6 my $h = $_[0];
413 6 ▶ $name = $h->{name} // '';
Condition100%2/2
$h->{"name"} // ""
l!l
15
MC/DC100%1/1
$h->{"name"} // ""
$h->{"name"}
Truth table100%2/2
A
A= $h->{"name"}
Aresult
11
00
414 6 ▶ croak "Expected 'action' element in hash" unless defined $h->{action};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $h->{"action"} 0 6 6
415 $logger->{printers}->{$name} = {
416 defined( $h->{min_level} ) ? ( min_level => $h->{min_level} ) : (),
417 defined( $h->{bitflags} ) ? ( bitflags => $h->{bitflags} ) : (),
418 action => $h->{action}
419 6 ▶ };
Branch: 2 branches
BranchTrueFalseTotal
defined $h->{'min_level'} ? : 1 5 6
defined $h->{'bitflags'} ? : 2 4 6
420 }
421 else {
422 0 croak "Expected single hash or 3 arguments";
423 }
424 }
425 elsif ( scalar(@_) == 0 ) {
426 return $logger->set_printer(
427 {
428 0 ▶ action => sub { print STDERR @_ }
Subroutine __ANON__: not called CC=1 SCAR=6.9
429 }
430 1 );
431 }
432 elsif ( scalar(@_) != 3 ) {
433 0 croak "Need name, min_level, action to define a back-end printer";
434 }
435 else {
436 0 ( $name, $level, $code ) = @_;
437 0 $logger->{printers}->{$name} = {
438 min_level => $level,
439 action => $code
440 };
441 }
442 6 return $logger;
443 }
444
445 =back
446
447 =head1 AUTHOR
448
449 Louis Strous <LS@quae.nl>
450
451 =head1 LICENSE AND COPYRIGHT
452
453 Copyright (c) 2016 Louis Strous.
454
455 This program is free software; you can redistribute it and/or modify
456 it under the same terms as Perl itself.
457
458 =cut
459
460 3 1;
« Synchronize/ProgressBar.pm ↑ Summary Synchronize/Timestamp.pm »