blib/lib/Log/Log4perl/Layout/JSON.pm

filter: Statementstmt 94.3% 184 / 195 Branchbran 78.5% 66 / 84 Conditioncond 69.4% 25 / 36 MC/DCmcdc 45.4% 10 / 22 Subroutinesub 100% 25 / 25 Podpod 0.0% 0 / 2 totaltotal 85.1% 310 / 364 CC 62 SCAR 23.9
CC
62
Cov
87%
render
24.4
_truncate_value
12.3
_process_field_values
9.2
CRAP 10.9
↑ Summary
1 package Log::Log4perl::Layout::JSON;
2 9 $Log::Log4perl::Layout::JSON::VERSION = '0.61';
3 # ABSTRACT: Layout a log message as a JSON hash, including MDC data
4  
5 9 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 9 ▶use parent qw(Log::Log4perl::Layout);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 9 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 9 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 9 ▶use Log::Log4perl ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 9 ▶use Log::Log4perl::Layout::PatternLayout;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 9 ▶use Log::Log4perl::Level;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 9 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 # TODO
19 # add eval around encode
20 # add way to include/exclude MDC items when include_mdc is enabled (eg by name and perhaps allow a regex)
21 # more tests
22 # consider ways to limit depth/breadth of encoded mdc data
23 # add overall message size limit
24  
25 9 ▶use Class::Tiny {
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 prefix => "",
28 format_prefix => 0,
29  
30 22 ▶ codec => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
31 22 return JSON::MaybeXS->new
32 ->indent(0) # to prevent newlines (and save space)
33 ->ascii(1) # to avoid encoding issues downstream
34 ->allow_unknown(1) # encode null on bad value (instead of exception)
35 ->convert_blessed(1) # call TO_JSON on blessed ref, if it exists
36 ->allow_blessed(1) # encode null on blessed ref that can't be converted
37 ;
38 },
39  
40 # mdc_handler is a code ref that, when called, returns name-value pairs
41 # of values from the MDC
42 22 ▶ mdc_handler => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
43 22 my $self = shift;
44  
45 22 ▶ return sub { } unless $self->include_mdc;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless $self->include_mdc 17 5 22
46  
47 5 my $mdc_hash = Log::Log4perl::MDC->get_context;
48  
49 5 ▶ if (my $mdc_field = $self->name_for_mdc) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mdc_field = $self->name_for_mdc) { } 2 3 5
50 5 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
51 5 ▶ return () unless %$mdc_hash;
Branch: 1 branch
BranchTrueFalseTotal
unless %$mdc_hash 3 2 5
52 2 return ($mdc_field => $mdc_hash);
53 2 };
54 }
55 else {
56 10 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
57 10 ▶ return %$mdc_hash unless $self->canonical;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->canonical 0 10 10
58 10 return map { $_ => $mdc_hash->{$_} } sort keys %$mdc_hash;
59 3 };
60 }
61 },
62  
63 1 ▶ field => sub {
Subroutine __ANON__: called CC=2 SCAR=7.4
64 1 my $self = shift;
65  
66 1 my $content = {};
67  
68 1 ▶ unless ($self->exclude_message) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->exclude_message) 0 1 1
69 0 $content->{message} = { value => '%m{chomp}' };
70 }
71  
72 1 return $content;
73 },
74 maxkb => undef,
75 canonical => 0,
76 include_mdc => 0,
77 exclude_message => 0,
78 name_for_mdc => undef,
79 max_json_length_kb => 20,
80  
81 # if format_prefix is true, the prefix is a PatternLayout that itself can be formatted
82 3 ▶ _prefix_layout => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
83 3 my $self = shift;
84  
85 3 return Log::Log4perl::Layout::PatternLayout->new($self->prefix);
86 },
87 9 };
88 9 ▶BEGIN { push our @ISA, 'Class::Tiny::Object' }
Subroutine BEGIN: called CC=1 SCAR=0.0
89  
90 9 my $last_render_error;
91  
92  
93 22 ▶sub BUILD { ## no critic (RequireArgUnpacking)
Subroutine BUILD: called CC=9 SCAR=22.1
Pod undocumented
94 22 my ($self, $args) = @_;
95  
96 22 delete $args->{value}; # => 'Log::Log4perl::Layout::JSON'
97  
98 22 ▶ if (my $arg = $args->{canonical}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $arg = $args->{"canonical"}) 22 0 22
99 22 $self->codec->canonical($arg->{value});
100 }
101  
102 22 ▶ if ($args->{field}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"field"}) 21 1 22
103 21 my $field = delete $args->{field};
104 21 $self->_build_field_values($field);
105 21 $self->field($field);
106 }
107  
108 22 ▶ if ($args->{maxkb}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args->{"maxkb"}) 2 20 22
109 2 my $maxkb = delete $args->{maxkb};
110  
111 2 $self->_build_maxkb_values($maxkb);
112  
113 2 $self->maxkb($maxkb);
114 }
115  
116 # Optionally override encoding from ascii to utf8
117 22 ▶ if (my $arg = $args->{utf8}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $arg = $args->{"utf8"}) 1 21 22
118 1 delete $args->{utf8};
119 1 $self->codec( $self->codec->ascii(0)->utf8(1) );
120 }
121  
122 22 for my $arg_name (qw(
123 canonical prefix include_mdc exclude_message name_for_mdc max_json_length_kb format_prefix
124 )) {
125 154 ▶ my $arg = delete $args->{$arg_name}
Branch: 1 branch
BranchTrueFalseTotal
my $arg = delete $args->{$arg_name} or next 46 108 154
126 or next;
127 46 $self->$arg_name( $arg->{value} );
128 }
129  
130 0 ▶ warn "Unknown configuration items: @{[ sort keys %$args ]}"
Branch: 1 branch
BranchTrueFalseTotal
if %$args 0 22 22
131 if %$args;
132  
133 #use Data::Dumper; warn Dumper $self;
134  
135 # sanity check to catch problems with the config at build time
136 22 if (1) {
137 22 undef $last_render_error;
138 22 $self->render("Testing $self config", "test", 1, 0);
139 22 ▶ die $last_render_error if $last_render_error;
Branch: 1 branch
BranchTrueFalseTotal
if $last_render_error 0 22 22
140 }
141  
142 22 return $self;
143 }
144  
145 74 ▶sub _process_field_values {
Subroutine _process_field_values: called CC=9 SCAR=22.2
146 74 my($self, $m, $category, $priority, $caller_level, $fields, $layed_out) = @_;
147  
148 74 $caller_level++;
149  
150 74 ▶ $fields //= $self->field;
Condition66%2/3
$fields //= $self->field
l!l&&r!l&&!r
24500
MC/DC0%0/2
$fields //= $self->field
$fields $self->field
Truth table66%2/3
A //= B
A= $fieldsB= $self->field
ABresult
1X1
011
000
151 74 ▶ $layed_out //= {};
Condition100%2/2
$layed_out //= {}
l!l
2450
MC/DC100%1/1
$layed_out //= {}
$layed_out
Truth table100%2/2
A
A= $layed_out
Aresult
11
00
152  
153 74 for my $field (keys %$fields) {
154 218 my $value = $fields->{$field};
155  
156 218 ▶ if (blessed($value) and blessed($value) eq 'Log::Log4perl::Layout::PatternLayout') {
Branch: 3 branches
BranchTrueFalseTotal
if (builtin::blessed($value) and builtin::blessed($value) eq 'Log::Log4perl::Layout::PatternLayout') { } 190 28 218
elsif (ref $value eq 'HASH') { } 24 4 28
elsif (ref $value eq 'CODE') { } 4 0 4
Condition66%2/3
builtin::blessed($value) and builtin::blessed($value) eq "Log::Log4perl::Layout::PatternLayout"
!ll&&!rl&&r
280190
MC/DC50%1/2
builtin::blessed($value) and builtin::blessed($value) eq "Log::Log4perl::Layout::PatternLayout"
builtin::blessed($value) builtin::blessed($value) eq "Log::Log4perl::Layout::PatternLayout"
Truth table66%2/3
A and B
A= builtin::blessed($value)B= builtin::blessed($value) eq "Log::Log4perl::Layout::PatternLayout"
ABresult
0X0
100
111
157 190 $layed_out->{$field} = $value->render($m, $category, $priority, $caller_level);
158 }
159 elsif (ref($value) eq 'HASH') {
160 24 ▶ $layed_out->{$field} //= {};
Condition50%1/2
$layed_out->{$field} //= {}
l!l
024
MC/DC0%0/1
$layed_out->{$field} //= {}
$layed_out->{$field}
Truth table50%1/2
A
A= $layed_out->{$field}
Aresult
11
00
161 24 $self->_process_field_values($m, $category, $priority, $caller_level, $value, $layed_out->{$field});
162 }
163 elsif (ref($value) eq 'CODE') {
164 4 $layed_out->{$field} = $value->($m, $category, $priority, $caller_level);
165 }
166 }
167  
168 74 return $layed_out;
169 }
170  
171 33 ▶sub _build_field_values {
Subroutine _build_field_values: called CC=7 SCAR=19.5
172  
173 33 my($self, $field_hash) = @_;
174  
175 33 for my $key (keys %$field_hash) {
176 100 my $value = $field_hash->{$key};
177 100 ▶ next unless ref $value eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 5 95 100
178  
179 95 ▶ if (exists $value->{value} && !ref($value->{value})) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $value->{'value'} and not ref $value->{'value'}) { } 81 14 95
elsif (exists $value->{'value'} and ref $value->{'value'} ne 'HASH') { } 2 12 14
Condition100%3/3
exists $value->{"value"} and not ref $value->{"value"}
!ll&&!rl&&r
6881
MC/DC100%2/2
exists $value->{"value"} and not ref $value->{"value"}
exists $value->{"value"} not ref $value->{"value"}
Truth table100%3/3
A and not(B)
A= exists $value->{"value"}B= not ref $value->{"value"}
ABresult
0X0
100
111
180 $field_hash->{$key} = Log::Log4perl::Layout::PatternLayout->new($value->{value})
181 81 }
182 ▶ elsif (exists $value->{value} && ref($value->{value}) ne 'HASH') {
Condition100%3/3
exists $value->{"value"} and ref $value->{"value"} ne "HASH"
!ll&&!rl&&r
662
MC/DC100%2/2
exists $value->{"value"} and ref $value->{"value"} ne "HASH"
exists $value->{"value"} ref $value->{"value"} ne "HASH"
Truth table100%3/3
A and B
A= exists $value->{"value"}B= ref $value->{"value"} ne "HASH"
ABresult
0X0
100
111
183 $field_hash->{$key} = $value->{value}
184 2 }
185 else {
186 12 $self->_build_field_values($value)
187 }
188 }
189 }
190  
191 4 ▶sub _build_maxkb_values {
Subroutine _build_maxkb_values: called CC=4 SCAR=13.9
192 4 my($self, $maxkb_hash) = @_;
193  
194 4 for my $key (keys %$maxkb_hash) {
195 4 my $value = $maxkb_hash->{$key};
196 4 ▶ if (exists $value->{value} && !ref($value->{value})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $value->{'value'} and not ref $value->{'value'}) { } 2 2 4
Condition66%2/3
exists $value->{"value"} and not ref $value->{"value"}
!ll&&!rl&&r
202
MC/DC50%1/2
exists $value->{"value"} and not ref $value->{"value"}
exists $value->{"value"} not ref $value->{"value"}
Truth table66%2/3
A and not(B)
A= exists $value->{"value"}B= not ref $value->{"value"}
ABresult
0X0
100
111
197 2 $maxkb_hash->{$key} = $value->{value};
198 }
199 else {
200 2 $self->_build_maxkb_values($value)
201 }
202 }
203 }
204  
205 8 ▶sub _truncate_value {
Subroutine _truncate_value: called CC=11 SCAR=25.1
206 8 my($self, $value_ref, $maxkb) = @_;
207  
208 8 ▶ return if !$value_ref || !${$value_ref};
Branch: 1 branch
BranchTrueFalseTotal
unless $value_ref and ${$value_ref;} 0 8 8
Condition33%1/3
$value_ref and ${$value_ref;}
!ll&&!rl&&r
008
MC/DC0%0/2
$value_ref and ${$value_ref;}
$value_ref ${$value_ref;}
Truth table33%1/3
A and B
A= $value_refB= ${$value_ref;}
ABresult
0X0
100
111
209 8 ▶ return if !$maxkb;
Branch: 1 branch
BranchTrueFalseTotal
unless $maxkb 0 8 8
210  
211 8 ▶ if (ref(${$value_ref}) eq 'HASH' && ref($maxkb) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref ${$value_ref;} eq 'HASH' and ref $maxkb eq 'HASH') { } 4 4 8
elsif (not ref ${$value_ref;} || ref $maxkb) { } 4 0 4
Condition66%2/3
ref ${$value_ref;} eq "HASH" and ref $maxkb eq "HASH"
!ll&&!rl&&r
404
MC/DC50%1/2
ref ${$value_ref;} eq "HASH" and ref $maxkb eq "HASH"
ref ${$value_ref;} eq "HASH" ref $maxkb eq "HASH"
Truth table66%2/3
A and B
A= ref ${$value_ref;} eq "HASH"B= ref $maxkb eq "HASH"
ABresult
0X0
100
111
212 4 for my $maxkb_key (keys %$maxkb) {
213 4 my $maxkb_val = $maxkb->{$maxkb_key};
214 4 ▶ next unless ${$value_ref}->{$maxkb_key};
Branch: 1 branch
BranchTrueFalseTotal
unless ${$value_ref;}->{$maxkb_key} 0 4 4
215  
216 4 $self->_truncate_value(\${$value_ref}->{$maxkb_key}, $maxkb_val)
217 }
218 }
219 4 ▶ elsif (!ref(${$value_ref}) && !ref($maxkb)) {
Condition33%1/3
ref ${$value_ref;} || ref $maxkb
l!l&&r!l&&!r
004
MC/DC0%0/2
ref ${$value_ref;} || ref $maxkb
ref ${$value_ref;} ref $maxkb
Truth table33%1/3
A || B
A= ref ${$value_ref;}B= ref $maxkb
ABresult
1X1
011
000
220 4 my $len = length ${$value_ref};
221 4 my $maxb = $maxkb * 1024;
222  
223 4 ▶ return if $len < $maxb;
Branch: 1 branch
BranchTrueFalseTotal
if $len < $maxb 2 2 4
224  
225 2 my $trunc_marker = "...[truncated, was $len chars total]...";
226 2 substr(${$value_ref}, $maxb - length($trunc_marker)) = $trunc_marker;
227 }
228 }
229  
230  
231 50 ▶sub render {
Subroutine render: called CC=22 SCAR=32.0
Pod undocumented
232 50 my($self, $message, $category, $priority, $caller_level) = @_;
233  
234 # increment caller_level to resolve caller appropriately
235 50 $caller_level++;
236  
237 50 my $m = '';
238 50 my @data = ();
239  
240 # Will receive array ref if "warp_message" appender option is set to "0"
241 50 ▶ if ( ref($message) eq 'ARRAY' and @{$message} > 1 and @{$message} % 2 == 0 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $message eq 'ARRAY' and @{$message;} > 1 and @{$message;} % 2 == 0) { } 2 48 50
elsif (ref $message eq 'ARRAY') { } 1 47 48
Condition83%5/6
ref $message eq "ARRAY" and @{$message;} > 1 and @{$message;} % 2 == 0
!ll&&!rl&&r
4712
ref $message eq "ARRAY" and @{$message;} > 1
!ll&&!rl&&r
4703
MC/DC66%2/3
ref $message eq "ARRAY" and @{$message;} > 1 and @{$message;} % 2 == 0
ref $message eq "ARRAY" @{$message;} > 1 @{$message;} % 2 == 0
Truth table75%3/4
A and B and C
A= ref $message eq "ARRAY"B= @{$message;} > 1C= @{$message;} % 2 == 0
ABCresult
0XX0
10X0
1100
1111
242 2 @data = @{$message};
243 2 $m = 'WARP_MESSAGE_0';
244 }
245 elsif ( ref($message) eq 'ARRAY' ) {
246 1 @data = @{$message};
247 1 $m = shift @data;
248 }
249 else {
250 47 $m = $message;
251 }
252  
253 50 my $layed_out_fields = $self->_process_field_values($m, $category, $priority, $caller_level);
254  
255 50 my @fields = (
256 %$layed_out_fields,
257 @data, # append extra fields but before mdc
258 $self->mdc_handler->($self) # MDC fields override non-MDC fields (not sure if this is a feature)
259 );
260  
261 # might need to remove dummy message
262 50 ▶ if ( $m eq 'WARP_MESSAGE_0' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m eq "WARP_MESSAGE_0") 2 48 50
263 2 ▶ for ( my $i = 0; $i < $#fields; $i += 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $#fields) 2 0 2
264 2 ▶ if ( $fields[$i] eq 'message' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fields[$i] eq "message") 2 0 2
265 2 splice( @fields, $i, 2 );
266 2 last;
267 }
268 }
269 }
270  
271 50 ▶ if (my $maxkb = $self->maxkb) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $maxkb = $self->maxkb) 4 46 50
272 4 ▶ for ( my $i = 0; $i < $#fields; $i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $#fields) 4 4 8
273 4 my($k, $v_ref) = ( $fields[$i], \$fields[$i+1] );
274  
275 4 my $field_maxkb = $maxkb->{$k};
276 4 ▶ next unless $field_maxkb;
Branch: 1 branch
BranchTrueFalseTotal
unless $field_maxkb 0 4 4
277  
278 4 $self->_truncate_value($v_ref, $field_maxkb);
279 }
280 }
281  
282 50 my $max_json_length = $self->max_json_length_kb * 1024;
283 50 my @dropped;
284 my $json;
285  
286 RETRY: {
287  
288 # MDC items might contain refs that cause encode to croak
289 # or the JSON might be too long
290 # so we fall-back to include progressively less data data
291 56 eval {
292 56 $json = $self->codec->encode(+{ @fields });
293  
294 56 ▶ die sprintf "length %d > %d\n", length($json), $max_json_length
Branch: 1 branch
BranchTrueFalseTotal
if length $json > $max_json_length 6 50 56
295 if length($json) > $max_json_length;
296 };
297 56 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 6 50 56
298 6 chomp $@;
299 6 my $encode_error = $@;
300  
301 # first look for any top-level field that's more than half of max_json_length
302 # for non-ref values truncate the string and add some explanatory text
303 # for ref values replace with undef
304 # this should catch most cases of an individual field that's too big
305 6 my @truncated;
306 6 for my $i (0 .. @fields/2) {
307 45 my ($k, $v) = ($fields[$i], $fields[$i+1]);
308  
309 # we use eval here to protect against fatal encoding errors
310 # (they'll get dealt with by the field pruning below)
311 45 my $len;
312 45 ▶ if (ref $v) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v) { } 0 45 45
313 0 my $encoded = eval { $self->codec->encode(+{ $k => $v }) };
314 0 ▶ if (not defined $encoded) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $encoded) 0 0 0
315 0 $fields[$i+1] = undef;
316 0 push @truncated, sprintf "%s %s set to undef after encoding error (%s)", $k, ref($v), $@;
317 0 next;
318 }
319 0 $len = length $encoded;
320 }
321 else {
322 45 ▶ $len = length($v) || 0;
Condition50%1/2
length $v || 0
l!l
450
MC/DC0%0/1
length $v || 0
length $v
Truth table50%1/2
A
A= length $v
Aresult
11
00
323 }
324 45 ▶ next if $len <= $max_json_length/2;
Branch: 1 branch
BranchTrueFalseTotal
if $len <= $max_json_length / 2 42 3 45
325  
326 3 ▶ if (ref $v) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v) { } 0 3 3
327 0 $fields[$i+1] = undef;
328 0 push @truncated, sprintf "truncated %s %s from %d to undef", $k, ref($v), $len;
329 }
330 else {
331 3 my $trunc_marker = sprintf("...[truncated, was %d chars total]...", $len);
332 3 substr($fields[$i+1], ($max_json_length/2) - length($trunc_marker)) = $trunc_marker;
333 3 push @truncated, sprintf "truncated %s from %d to %d", $k, $len, length($fields[$i+1]);
334 }
335 }
336  
337 6 my $msg;
338 6 ▶ if (@truncated) {
Branch: 1 branch
BranchTrueFalseTotal
if (@truncated) { } 2 4 6
339 2 $msg = join(", ", @truncated).", retrying";
340 }
341 else {
342 4 my ($name) = splice @fields, -2;
343 4 push @dropped, $name;
344 4 $msg = "retrying without ".join(", ", @dropped);
345 }
346  
347 # TODO get smarter here, especially if name_for_mdc is being used.
348 #
349 # Could encode each field and order by size then discard from top down.
350 # Note: if we edit any refs we'd need to edit clones
351 # If the 'message' field itself is > $max_json_length/2 then truncate
352 # the message to $max_json_length/2 first so we don't loose all the context data.
353 # Add an extra field to indicate truncation has happened?
354  
355  
356 6 $last_render_error = sprintf "Error encoding %s: %s (%s)",
357 ref($self), $encode_error, $msg;
358 # avoid warn due to recursion risk
359 6 print STDERR "$last_render_error\n";
360  
361 6 ▶ goto RETRY if @fields;
Branch: 1 branch
BranchTrueFalseTotal
if @fields 6 0 6
362 }
363 }
364  
365 50 my $prefix = $self->prefix;
366  
367 50 ▶ if ($self->format_prefix) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->format_prefix) { } 6 44 50
368 6 return $self->_prefix_layout->render($message, $category, $priority, $caller_level) . $json . "\n";
369 }
370 else {
371 44 return $self->prefix . $json . "\n";
372 }
373 }
374  
375 9 1;
376  
377 __END__
↑ Summary