Circle/Loggable.pm

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