File Coverage

blib/lib/Log/Log4perl/Layout/JSON/Readable.pm
Criterion Covered Total %
statement 37 37 100.0
branch 5 6 83.3
condition 1 3 33.3
subroutine 8 8 100.0
pod 0 3 0.0
total 51 57 89.4


line stmt bran cond sub pod time code
1             package Log::Log4perl::Layout::JSON::Readable;
2              
3 1     1   3112 use strict;
  1         2  
  1         26  
4 1     1   4 use warnings;
  1         2  
  1         26  
5 1     1   4 use parent 'Log::Log4perl::Layout::JSON';
  1         2  
  1         6  
6             our $VERSION = '1.0.1'; # VERSION
7             # ABSTRACT: JSON layout, but some fields always come first
8              
9             use Class::Tiny +{
10 2         17 first_fields => sub { [qw(time pid level)] },
11 1     1   5459 };
  1         2  
  1         6  
12              
13              
14             sub BUILDARGS {
15 3     3 0 8723 my ($class, @etc) = @_;
16             # the parent class does not have a BUILDARGS, but it may get one
17             # in the future, let's handle both cases
18 3   33     18 my $args = $class->maybe::next::method(@etc) || $etc[0];
19              
20 3 100       77 if (my $first_fields = delete $args->{first_fields}) {
21             $args->{first_fields} = [
22 2         9 grep { length }
23 2         17 map { my $v = $_; $v =~ s/\s+//g; $v }
  2         4  
  2         5  
24             split /\s*,\s*/,
25             $first_fields->{value},
26 1         7 ];
27             }
28              
29 3         9 return $args;
30             }
31              
32             # HACK!! the parent class Cs when it sees an argument it doesn't
33             # expect. To prevent that, we consume it first
34             sub BUILDALL {
35 3     3 0 58 my ($self, $args, @etc) = @_;
36              
37 3 100       8 if (my $first_fields = delete $args->{first_fields}) {
38 1         20 $self->first_fields($first_fields);
39             }
40              
41 3         19 return $self->next::method($args,@etc);
42             }
43              
44             sub render {
45 6     6 0 3106 my $self = shift;
46              
47 6         20 my $json = $self->SUPER::render(@_);
48              
49 6 50       4185 if (my $first_fields = $self->first_fields) {
50 6         23 for my $key (reverse @{$first_fields}) {
  6         13  
51 16         30 _move_field_first(\$json, $key);
52             }
53             }
54              
55 6         19 return $json;
56             }
57              
58             sub _move_field_first {
59 16     16   27 my ($json_ref, $key) = @_;
60 16         20 ${$json_ref} =~ s/^{(.+?),("$key":".+?")/\{$2,$1/;
  16         259  
61 16         42 return;
62             }
63              
64             1;
65              
66             __END__