blib/lib/Circle/Loggable.pm

filter: Statementstmt 23.9% 50 / 209 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 42.4% 14 / 33 Podpod 0.0% 0 / 10 totaltotal 19.1% 64 / 334 SCAR 67.9
CC
39
Cov
18%
split_logpath
110.0
logger
90.0
command_log_info
30.0
CRAP 889.8
« blib/lib/Circle/Collection.pm ↑ Summary blib/lib/Circle/Rule/Store.pm »
1 # You may distribute under the terms of the GNU General Public License
2 #
3 # (C) Paul Evans, 2014 -- leonerd@leonerd.org.uk
4  
5 package Circle::Loggable;
6  
7 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use base qw( Circle::Commandable Circle::Configurable );
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶use File::Basename qw( dirname );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 ▶use File::Path qw( make_path );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use POSIX qw( strftime mktime );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 4 __PACKAGE__->APPLY_Inheritable_Setting( log_enabled =>
16 description => "Enable logging of events",
17 type => 'bool',
18 );
19  
20 4 __PACKAGE__->APPLY_Inheritable_Setting( log_path =>
21 description => "Path template for log file name",
22 type => 'str',
23 );
24  
25 4 ▶use Struct::Dumb qw( readonly_struct );
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 # Data about the log file itself
28 4 readonly_struct LogId => [qw(
29 path time_start time_until itempath line_timestamp_fmt
30 )];
31  
32 # Data about logging from a particular item
33 4 readonly_struct LogCtx => [qw(
34 path_residue
35 )];
36  
37 4 our $NO_LOG = 0;
38  
39 sub push_log
40 {
41 0 ▶ my $self = shift;
Subroutine push_log: not called CC=4 SCAR=30.0
Pod undocumented
42 0 my ( $event, $time, $args ) = @_;
43  
44 0 ▶ return unless $self->setting_log_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->setting_log_enabled 0 0 0
45 0 ▶ return if $NO_LOG;
Branch: 1 branch
BranchTrueFalseTotal
if $Circle::Loggable::NO_LOG 0 0 0
46  
47 # Best-effort
48 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $logger = $self->logger($time); my $ctx = $self->{"logctx"}; $logger->log($ctx, $time, $event, $args); 1 } } and return 0 0 0
49 0 my $logger = $self->logger( $time );
50  
51 0 my $ctx = $self->{logctx};
52  
53 0 $logger->log( $ctx, $time, $event, $args );
54 0 1;
55 } and return;
56  
57 {
58 0 local $NO_LOG = 1;
59 0 warn "Unable to log - $@";
60 }
61 }
62  
63 4 my %time_format_to_idx = (
64 Y => 5,
65 m => 4,
66 d => 3,
67 H => 2,
68 M => 1,
69 S => 0,
70 );
71  
72 # Returns a LogId and a LogCtx
73 sub split_logpath
74 {
75 0 ▶ my $self = shift;
Subroutine split_logpath: not called CC=10 SCAR=47.0
Pod undocumented
76 0 my ( $time ) = @_;
77  
78 0 my @pcs = split m{/}, $self->enumerable_path;
79 0 shift @pcs; # trim leading /
80 0 ▶ @pcs or @pcs = ( "Global" );
Branch: 1 branch
BranchTrueFalseTotal
@pcs or @pcs = "Global" 0 0 0
81 0 my $path_used = 0;
82 0 my %ts_used = map { $_ => 0 } qw( Y m d H M );
83  
84 0 my @timestamp = localtime $time;
85  
86 my %formats = (
87 # Specific kinds of time format so we can track the granulity being used
88 ( map {
89 0 my $format = $_;
90 $format => sub {
91 0 ▶ $ts_used{$format}++;
Subroutine __ANON__: not called CC=1 SCAR=6.9
92 0 strftime( "%$format", @timestamp )
93 0 };
94 } qw( Y m d H M ) ),
95 P => sub {
96 0 ▶ my ( $limit ) = @_;
Subroutine __ANON__: not called CC=4 SCAR=30.0
97 0 ▶ defined $limit or $limit = @pcs;
Branch: 1 branch
BranchTrueFalseTotal
defined $limit or $limit = @pcs 0 0 0
98  
99 0 my $path_lower = $path_used;
100 0 my $path_upper = $limit;
101  
102 0 ▶ $path_used = $path_upper if $path_upper > $path_used;
Branch: 1 branch
BranchTrueFalseTotal
if $path_upper > $path_used 0 0 0
103  
104 0 ▶ return join '/', map { $_ // "" } @pcs[$path_lower..$path_upper-1];
Condition0%0/2
$_ // ""
l!l
00
MC/DC0%0/1
$_ // ""
$_
Truth table0%0/2
A
A= $_
Aresult
11
00
105 },
106 0 );
107  
108 0 my $path = $self->setting_log_path;
109 0 $path =~ s<%(?:{([^}]*)})?(.)>
110 0 ▶ {exists $formats{$2} ? $formats{$2}->($1)
Branch: 1 branch
BranchTrueFalseTotal
exists $formats{$2} ? : 0 0 0
111 : die "Unrecognised escape '%$2"}eg;
112  
113 # Reset to zero all the fields that aren't used
114 0 ▶ $ts_used{$_} or $timestamp[$time_format_to_idx{$_}] = 0 for qw( Y m d H M S );
Branch: 1 branch
BranchTrueFalseTotal
$ts_used{$_} or $timestamp[$time_format_to_idx{$_}] = 0 0 0 0
115 0 ▶ $timestamp[3] or $timestamp[3] = 1; # mday is 1-based
Branch: 1 branch
BranchTrueFalseTotal
$timestamp[3] or $timestamp[3] = 1 0 0 0
116  
117 0 my $time_start = strftime( "%Y/%m/%d %H:%M:%S", @timestamp );
118  
119 # Increment the last timestamp field before a field not used in the file
120 # path
121 0 ▶ $ts_used{$_} or $timestamp[$time_format_to_idx{$_}+1]++, last for qw( m d H M S );
Branch: 1 branch
BranchTrueFalseTotal
$ts_used{$_} or ++$timestamp[$time_format_to_idx{$_} + 1], last 0 0 0
122 0 my $time_until = mktime @timestamp;
123  
124 0 ▶ my $time_fmt_day = join "/", map { $ts_used{$_} ? () : ( "\%$_" ) } qw( Y m d );
Branch: 1 branch
BranchTrueFalseTotal
$ts_used{$_} ? : 0 0 0
125 0 ▶ my $time_fmt_sec = join ":", map { $ts_used{$_} ? () : ( "\%$_" ) } qw( H M S );
Branch: 1 branch
BranchTrueFalseTotal
$ts_used{$_} ? : 0 0 0
126  
127 my $logid = LogId(
128 $path,
129 $time_start,
130 $time_until,
131 0 join( '/', grep { defined } @pcs[0..$path_used-1] ),
132 0 join( " ", grep { length } $time_fmt_day, $time_fmt_sec ),
133 );
134  
135 my $logctx = LogCtx(
136 0 join( '/', grep { defined } @pcs[$path_used..$#pcs] ),
137 );
138  
139 0 return ( $logid, $logctx );
140 }
141  
142 4 our %LOGGER_FOR_PATH;
143  
144 sub logger
145 {
146 0 ▶ my $self = shift;
Subroutine logger: not called CC=9 SCAR=45.0
Pod undocumented
147 0 my ( $time ) = @_;
148  
149 0 my ( $logid, $logctx ) = $self->split_logpath( $time );
150 0 my $path = $logid->path;
151  
152 0 ▶ if( defined $self->{logpath} and $self->{logpath} ne $path ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"logpath"} and $self->{"logpath"} ne $path) 0 0 0
Condition0%0/3
defined $self->{"logpath"} and $self->{"logpath"} ne $path
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"logpath"} and $self->{"logpath"} ne $path
defined $self->{"logpath"} $self->{"logpath"} ne $path
Truth table0%0/3
A and B
A= defined $self->{"logpath"}B= $self->{"logpath"} ne $path
ABresult
0X0
100
111
153 0 $self->close_logger;
154 }
155 0 ▶ if( defined $self->{loguntil} and $time >= $self->{loguntil} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"loguntil"} and $time >= $self->{"loguntil"}) 0 0 0
Condition0%0/3
defined $self->{"loguntil"} and $time >= $self->{"loguntil"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"loguntil"} and $time >= $self->{"loguntil"}
defined $self->{"loguntil"} $time >= $self->{"loguntil"}
Truth table0%0/3
A and B
A= defined $self->{"loguntil"}B= $time >= $self->{"loguntil"}
ABresult
0X0
100
111
156 0 $self->close_logger;
157 }
158  
159 0 ▶ my $logger = $LOGGER_FOR_PATH{$path} ||= do {
Condition0%0/3
$Circle::Loggable::LOGGER_FOR_PATH{$path} ||= do { my $dir = dirname($path); unless (-d $dir) { make_path($dir, {"mode", 448}) or die "Cannot mkdir $dir - $!"; } ; "Circle::Loggable::Backend::CircleLog"->open($logid) }
l!l&&r!l&&!r
000
MC/DC0%0/2
$Circle::Loggable::LOGGER_FOR_PATH{$path} ||= do { my $dir = dirname($path); unless (-d $dir) { make_path($dir, {"mode", 448}) or die "Cannot mkdir $dir - $!"; } ; "Circle::Loggable::Backend::CircleLog"->open($logid) }
$Circle::Loggable::LOGGER_FOR_PATH{$path} do { my $dir = dirname($path); unless (-d $dir) { make_path($dir, {"mode", 448}) or die "Cannot mkdir $dir - $!"; } ; "Circle::Loggable::Backend::CircleLog"->open($logid) }
Truth table0%0/3
A ||= B
A= $Circle::Loggable::LOGGER_FOR_PATH{$path}B= do { my $dir = dirname($path); unless (-d $dir) { make_path($dir, {"mode", 448}) or die "Cannot mkdir $dir - $!"; } ; "Circle::Loggable::Backend::CircleLog"->open($logid) }
ABresult
1X1
011
000
160 0 my $dir = dirname( $path );
161 0 ▶ unless( -d $dir ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir) 0 0 0
162 0 ▶ make_path( $dir, { mode => 0700 } ) or die "Cannot mkdir $dir - $!";
Branch: 1 branch
BranchTrueFalseTotal
make_path($dir, {"mode", 448}) or die "Cannot mkdir $dir - $!" 0 0 0
163 }
164  
165 0 Circle::Loggable::Backend::CircleLog->open( $logid );
166 };
167  
168 0 ▶ if( !defined $self->{logpath} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"logpath"}) 0 0 0
169 0 $self->{logpath} = $path;
170 0 $self->{loguntil} = $logid->time_until;
171 0 $logger->hold_ref;
172  
173 # TODO set up a timer to expire and close the log at that time
174 }
175  
176 0 $self->{logctx} = $logctx;
177  
178 0 return $logger;
179 }
180  
181 sub close_logger
182 {
183 0 ▶ my $self = shift;
Subroutine close_logger: not called CC=3 SCAR=24.8
Pod undocumented
184  
185 0 ▶ my $logger = $LOGGER_FOR_PATH{$self->{logpath}} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $logger = $Circle::Loggable::LOGGER_FOR_PATH{$self->{"logpath"}} or return 0 0 0
186  
187 0 $logger->drop_ref;
188 0 ▶ if( !$logger->refcount ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($logger->refcount) 0 0 0
189 0 delete $LOGGER_FOR_PATH{$self->{logpath}};
190 0 $logger->close;
191 }
192  
193 0 undef $self->{logpath};
194 }
195  
196 sub command_log
197 : Command_description("Configure logging")
198 ▶{
Subroutine command_log: not called CC=1 SCAR=0.0
Pod undocumented
199 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
200  
201 sub command_log_info
202 : Command_description("Show information about logging")
203 : Command_subof('log')
204 : Command_default()
205 {
206 0 ▶ my $self = shift;
Subroutine command_log_info: not called CC=5 SCAR=34.0
Pod undocumented
207 0 my ( $cinv ) = @_;
208  
209 0 ▶ if( $self->_setting_log_enabled_inherits ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_setting_log_enabled_inherits) { } 0 0 0
elsif ($self->setting_log_enabled) { } 0 0 0
210 0 ▶ $cinv->respond( "Logging is inherited (currently " . ( $self->setting_log_enabled ? "enabled" : "disabled" ) . ")" );
Branch: 1 branch
BranchTrueFalseTotal
$self->setting_log_enabled ? : 0 0 0
211 }
212 elsif( $self->setting_log_enabled ) {
213 0 $cinv->respond( "Logging is directly enabled" );
214 }
215 else {
216 0 $cinv->respond( "Logging is directly disabled" );
217 }
218  
219 0 ▶ if( $self->setting_log_enabled ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->setting_log_enabled) 0 0 0
220 0 my ( $logid, $logctx ) = $self->split_logpath( time );
221  
222 0 $cinv->respond( "Logging to path " . $logid->path );
223 0 $cinv->respond( "Timestamp starts " . $logid->time_start );
224 0 $cinv->respond( "Timestamp until " . strftime( "%Y/%m/%d %H:%M:%S", localtime $logid->time_until ) );
225 0 $cinv->respond( "Line timestamp is " . $logid->line_timestamp_fmt );
226  
227 0 $cinv->respond( "Path residue is " . $logctx->path_residue );
228 }
229  
230 0 return;
231 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
232  
233 sub command_log_enable
234 : Command_description("Enable logging of this item and its children")
235 : Command_subof('log')
236 {
237 0 ▶ my $self = shift;
Subroutine command_log_enable: not called CC=1 SCAR=6.9
Pod undocumented
238 0 my ( $cinv ) = @_;
239  
240 0 $self->setting_log_enabled( 1 );
241 0 $cinv->respond( "Logging enabled" );
242 0 return;
243 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
244  
245 sub command_log_disable
246 : Command_description("Disable logging of this item and its children")
247 : Command_subof('log')
248 {
249 0 ▶ my $self = shift;
Subroutine command_log_disable: not called CC=1 SCAR=6.9
Pod undocumented
250 0 my ( $cinv ) = @_;
251  
252 0 $self->setting_log_enabled( 0 );
253 0 $cinv->respond( "Logging disabled" );
254 0 return;
255 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
256  
257 sub command_log_inherit
258 : Command_description("Inherit log enabled state from parent")
259 : Command_subof('log')
260 {
261 0 ▶ my $self = shift;
Subroutine command_log_inherit: not called CC=2 SCAR=17.9
Pod undocumented
262 0 my ( $cinv ) = @_;
263  
264 0 $self->setting_log_enabled( undef );
265 0 ▶ $cinv->respond( "Logging inherited (currently " . $self->setting_log_enabled ? "enabled" : "disabled" );
Branch: 1 branch
BranchTrueFalseTotal
'Logging inherited (currently ' . $self->setting_log_enabled ? : 0 0 0
266 0 return;
267 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
268  
269 sub command_log_rotate
270 : Command_description("Rotate the current log file handle")
271 : Command_subof('log')
272 {
273 0 ▶ my $self = shift;
Subroutine command_log_rotate: not called CC=3 SCAR=24.8
Pod undocumented
274 0 my ( $cinv ) = @_;
275  
276 0 my $path;
277 0 my $n_suffix = 1;
278 0 ▶ $n_suffix++ while -f ( $path = "$self->{logpath}.$n_suffix" );
Branch: 1 branch
BranchTrueFalseTotal
-f ($path = qq[$self->{"logpath"}.$n_suffix]) and do { ++$n_suffix } 0 0 0
279  
280 0 ▶ unless( rename( $self->{logpath}, $path ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (rename $self->{"logpath"}, $path) 0 0 0
281 0 $cinv->responderr( "Cannot rename $self->{logpath} to $path - $!" );
282 0 return;
283 }
284  
285 0 $cinv->respond( "Log file rotated to $path" );
286  
287 0 $self->{logger}->close;
288 0 undef $self->{logger};
289  
290 0 return;
291 4 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
292  
293 package # hide
294 Circle::Loggable::Backend::CircleLog;
295  
296 4 ▶use POSIX qw( strftime );
Subroutine BEGIN: called CC=1 SCAR=0.0
297  
298 sub open
299 {
300 0 ▶ my $class = shift;
Subroutine open: not called CC=2 SCAR=17.9
301 0 my ( $id ) = @_;
302  
303 0 my $path = $id->path;
304 0 ▶ open my $fh, ">>", $path or die "Cannot open event log $path - $!";
Branch: 1 branch
BranchTrueFalseTotal
CORE::open my $fh, ">>", $path or die "Cannot open event log $path - $!" 0 0 0
305 0 chmod $fh, 0600;
306  
307 0 $fh->binmode( ":encoding(UTF-8)" );
308 0 $fh->autoflush;
309  
310 0 $fh->print( "!LOG START=\"${\$id->time_start}\" ITEMS=\"${\$id->itempath}\" TIMESTAMP_FMT=\"${\$id->line_timestamp_fmt}\"\n" );
311  
312 0 return bless {
313 fh => $fh,
314 refcount => 0,
315 id => $id,
316 }, $class;
317 }
318  
319 0 ▶sub refcount { shift->{refcount} }
Subroutine refcount: not called CC=1 SCAR=6.9
320 0 ▶sub hold_ref { shift->{refcount}++ }
Subroutine hold_ref: not called CC=1 SCAR=6.9
321 0 ▶sub drop_ref { shift->{refcount}-- }
Subroutine drop_ref: not called CC=1 SCAR=6.9
322  
323 sub close
324 {
325 0 ▶ my $self = shift;
Subroutine close: not called CC=2 SCAR=17.9
326 0 ▶ warn "Closing $self with references open" if $self->{refcount};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"refcount"} 0 0 0
327  
328 0 close $self->{fh};
329 }
330  
331 sub log
332 {
333 0 ▶ my $self = shift;
Subroutine log: not called CC=2 SCAR=17.9
334 0 my ( $ctx, $time, $event, $args ) = @_;
335  
336 0 my $line = strftime( $self->{id}->line_timestamp_fmt, localtime $time );
337 0 ▶ $line .= " ".$ctx->path_residue if length $ctx->path_residue;
Branch: 1 branch
BranchTrueFalseTotal
if length $ctx->path_residue 0 0 0
338 0 $line .= " $event";
339 0 $line .= " ".$self->encode( $args );
340 0 $line .= "\n";
341  
342 0 $self->{fh}->print( $line );
343 }
344  
345 ## This should output a valid YAML encoding of a data tree, on a single line
346 # using flow-style mappings and sequences
347 # Similar to JSON except without quoted keys
348  
349 sub encode
350 {
351 0 ▶ my $self = shift;
Subroutine encode: not called CC=4 SCAR=30.0
352 0 my ( $args ) = @_;
353  
354 0 ▶ if( !ref $args ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $args) { } 0 0 0
elsif (ref $args eq 'HASH') { } 0 0 0
elsif (ref $args eq 'ARRAY') { } 0 0 0
355 0 my $str = "$args";
356 0 $str =~ s/(["\\])/\\$1/g;
357 0 $str =~ s/\n/\\n/g;
358 0 $str =~ s/\t/\\t/g;
359 0 $str =~ s/([\x00-\x1f\x80-\x9f])/sprintf "\\x%02x", ord $1/eg;
360 0 return qq("$str");
361 }
362 elsif( ref $args eq "HASH" ) {
363 return "{" . join( ", ", map {
364 0 "$_: ".$self->encode( $args->{$_} )
365 } sort keys %$args ) . "}";
366 }
367 elsif( ref $args eq "ARRAY" ) {
368 return "[" . join( ", ", map {
369 0 $self->encode( $args->[$_] )
370 } 0 .. $#$args ) . "]";
371 }
372 else {
373 0 return "$args";
374 }
375 }
376  
377 4 0x55AA;
« blib/lib/Circle/Collection.pm ↑ Summary blib/lib/Circle/Rule/Store.pm »