blib/lib/Log/Any/Adapter/DERIV.pm

filter: Statementstmt 92.8% 181 / 195 Branchbran 84.2% 32 / 38 Conditioncond 75.8% 22 / 29 MC/DCmcdc 64.7% 11 / 17 Subroutinesub 92.8% 39 / 42 Podpod 87.5% 7 / 8 totaltotal 88.7% 292 / 329 CC 37 SCAR 15.4
CC
37
Cov
90%
new
13.1
__ANON__
12.2
format_line
5.1
CRAP 4.7
↑ Summary
1 package Log::Any::Adapter::DERIV;
2 # ABSTRACT: one company's example of a standardised logging setup
3  
4 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 7 our $AUTHORITY = 'cpan:DERIV'; # AUTHORITY
8 7 our $VERSION = '0.009';
9  
10 7 ▶use feature qw(state);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use parent qw(Log::Any::Adapter::Coderef);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use Syntax::Keyword::Try;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 7 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 =encoding utf8
17  
18 =head1 NAME
19  
20 Log::Any::Adapter::DERIV - standardised logging to STDERR and JSON file
21  
22 =begin markdown
23  
24 [![Test status](https://circleci.com/gh/binary-com/perl-Log-Any-Adapter-DERIV.svg?style=shield&circle-token=bed2af8f8e388746eafbbf905cf6990f84dbd69e)](https://app.circleci.com/pipelines/github/binary-com/perl-Log-Any-Adapter-DERIV)
25  
26 =end markdown
27  
28 =head1 SYNOPSIS
29  
30 use Log::Any;
31  
32 # print text log to STDERR, json format when inside docker container,
33 # colored text format when STDERR is a tty, non-colored text format when
34 # STDERR is redirected.
35 use Log::Any::Adapter ('DERIV');
36  
37 #specify STDERR directly
38 use Log::Any::Adapter ('DERIV', stderr => 1)
39  
40 #specify STDERR's format
41 use Log::Any::Adapter ('DERIV', stderr => 'json')
42  
43 #specify the json log name
44 use Log::Any::Adapter ('DERIV', json_log_file => '/var/log/program.json.log');
45  
46 =head1 DESCRIPTION
47  
48 Applies some opinionated log handling rules for L<Log::Any>.
49  
50 B<This is extremely invasive>. It does the following, affecting global state
51 in various ways:
52  
53 =over 4
54  
55 =item * applies UTF-8 encoding to STDERR
56  
57 =item * writes to a C<.json.log> file.
58  
59 =item * overrides the default L<Log::Any::Proxy> formatter to provide data as JSON
60  
61 =item * when stringifying, may replace some problematic objects with simplified versions
62  
63 =back
64  
65 An example of the string-replacement approach would be the event loop in asynchronous code:
66 it's likely to have many components attached to it, and dumping that would effectively end up
67 dumping the entire tree of useful objects in the process. This is a planned future extension,
68 not currently implemented.
69  
70 =head2 Why
71  
72 This is provided as a CPAN module as an example for dealing with multiple outputs and formatting.
73 The existing L<Log::Any::Adapter> modules tend to cover one thing, and it's
74 not immediately obvious how to extend formatting, or send data to multiple logging mechanisms at once.
75  
76 Although the module may not be directly useful, it is hoped that other teams may find
77 parts of the code useful for their own logging requirements.
78  
79 There is a public repository on Github, anyone is welcome to fork that and implement
80 their own version or make feature/bug fix suggestions if they seem generally useful:
81  
82 L<https://github.com/binary-com/perl-Log-Any-Adapter-DERIV>
83  
84 =head2 PARAMETERS
85  
86 =over 4
87  
88 =item * json_log_file
89  
90 Specify a file name to which you want the json formatted logs printed into.
91 If not given, then it prints the logs to STDERR.
92  
93 =item * STDERR
94  
95 If it is true, then print logs to STDERR
96  
97 If the value is json or text, then print logs with that format
98  
99 If the value is just a true value other than `json` or `text`,
100 then if it is running in a container, then it prints the logs in `json` format.
101 Else if STDERR is a tty, then it prints `colored text` format.
102 Else it prints non-color text format.
103  
104 =back
105  
106 If no parameters provided, then default `stderr => 1`;
107  
108 =cut
109  
110 =head1 METHODS
111  
112 =cut
113  
114 7 ▶use Time::Moment;
Subroutine BEGIN: called CC=1 SCAR=0.0
115 7 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
116 7 ▶use curry;
Subroutine BEGIN: called CC=1 SCAR=0.0
117 7 ▶use JSON::MaybeUTF8 qw(:v1);
Subroutine BEGIN: called CC=1 SCAR=0.0
118 7 ▶use PerlIO;
Subroutine BEGIN: called CC=1 SCAR=0.0
119 7 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
120 7 ▶use Term::ANSIColor;
Subroutine BEGIN: called CC=1 SCAR=0.0
121 7 ▶use Log::Any qw($log);
Subroutine BEGIN: called CC=1 SCAR=0.0
122 7 ▶use Fcntl qw(:DEFAULT :seek :flock);
Subroutine BEGIN: called CC=1 SCAR=0.0
123 7 ▶use Log::Any::Adapter::Util qw(numeric_level logging_methods);
Subroutine BEGIN: called CC=1 SCAR=0.0
124 7 ▶use Clone qw(clone);
Subroutine BEGIN: called CC=1 SCAR=0.0
125  
126 # Used for stringifying data more neatly than Data::Dumper might offer
127 7 our $JSON = JSON::MaybeXS->new(
128 # Multi-line for terminal output, single line if redirecting somewhere
129 pretty => _fh_is_tty(\*STDERR),
130 # Be consistent
131 canonical => 1,
132 # Try a bit harder to give useful output
133 convert_blessed => 1,
134 );
135  
136 # Simple mapping from severity levels to Term::ANSIColor definitions.
137 7 our %SEVERITY_COLOUR = (
138 trace => [qw(grey12)],
139 debug => [qw(grey18)],
140 info => [qw(green)],
141 warning => [qw(bright_yellow)],
142 error => [qw(red bold)],
143 fatal => [qw(red bold)],
144 critical => [qw(red bold)],
145 );
146  
147 7 my $adapter_context;
148 7 my @methods = reverse logging_methods();
149 7 my %num_to_name = map { $_ => $methods[$_] } 0 .. $#methods;
150  
151 # The obvious way to handle this might be to provide our own proxy class:
152 # $Log::Any::OverrideDefaultProxyClass = 'Log::Any::Proxy::DERIV';
153 # but the handling for proxy classes is somewhat opaque - and there's an ordering problem
154 # where `use Log::Any` before the adapter is loaded means we end up with some classes having
155 # the default anyway.
156 # Rather than trying to deal with that, we just provide our own default:
157 {
158 7 ▶ no warnings 'redefine'; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
159  
160 # We expect this to be loaded, but be explicit just in case - we'll be overriding
161 # one of the methods, so let's at least make sure it exists first
162 7 require Log::Any::Proxy;
163  
164 # Mostly copied from Log::Any::Proxy
165 0 ▶ *Log::Any::Proxy::_default_formatter = sub {
Subroutine __ANON__: not called CC=4 SCAR=25.0
166 0 my ($cat, $lvl, $format, @params) = @_;
167 0 ▶ return $format->() if ref($format) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $format eq "CODE" 0 0 0
168  
169 chomp(
170 my @new_params = map {
171 0 ▶ eval { $JSON->encode($_) }
Condition0%0/3
eval { do { $Log::Any::Adapter::DERIV::JSON->encode($_) } } // Log::Any::Proxy::_stringify_params($_)
l!l&&r!l&&!r
000
MC/DC0%0/2
eval { do { $Log::Any::Adapter::DERIV::JSON->encode($_) } } // Log::Any::Proxy::_stringify_params($_)
eval { do { $Log::Any::Adapter::DERIV::JSON->encode($_) } } Log::Any::Proxy::_stringify_params($_)
Truth table0%0/3
A // B
A= eval { do { $Log::Any::Adapter::DERIV::JSON->encode($_) } }B= Log::Any::Proxy::_stringify_params($_)
ABresult
1X1
011
000
172 // Log::Any::Proxy::_stringify_params($_)
173 } @params
174 );
175 0 s{\n}{\n }g for @new_params;
176  
177 # Perl 5.22 adds a 'redundant' warning if the number parameters exceeds
178 # the number of sprintf placeholders. If a user does this, the warning
179 # is issued from here, which isn't very helpful. Doing something
180 # clever would be expensive, so instead we just disable warnings for
181 # the final line of this subroutine.
182 7 ▶ no warnings; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
183 0 return sprintf($format, @new_params);
184 7 };
185 }
186  
187 # Upgrade any `warn ...` lines to send through Log::Any.
188 0 ▶$SIG{__WARN__} = sub { ## no critic (RequireLocalizedPunctuationVars)
Subroutine __ANON__: not called CC=1 SCAR=6.9
189 # We don't expect anything called from here to raise further warnings, but
190 # let's be safe and try to avoid any risk of recursion
191 0 local $SIG{__WARN__} = undef;
192 0 chomp(my $msg = shift);
193 0 $log->warn($msg);
194 7 };
195  
196 184 ▶sub new {
Subroutine new: called CC=13 SCAR=25.8
Pod undocumented
197 184 my ($class, %args) = @_;
198 184 ▶ my $self = $class->SUPER::new(sub { }, %args);
Subroutine __ANON__: not called CC=1 SCAR=0.0
199  
200 # if there is json_log_file, then print json to that file
201 184 ▶ if ($self->{json_log_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"json_log_file"}) 110 74 184
202 110 ▶ $self->{json_fh} = path($self->{json_log_file})->opena_utf8 or die 'unable to open log file - ' . $!;
Branch: 1 branch
BranchTrueFalseTotal
$self->{"json_fh"} = path($self->{"json_log_file"})->opena_utf8 or die 'unable to open log file - ' . $! 110 0 110
203 110 $self->{json_fh}->autoflush(1);
204 }
205  
206 # if there is stderr, then print log to stderr also
207 # if stderr is json or text, then use that format
208 # else, if it is in_container, then json, else text
209 184 ▶ if (!$self->{json_log_file} && !$self->{stderr}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"json_log_file"} or $self->{"stderr"}) 50 134 184
Condition100%3/3
$self->{"json_log_file"} or $self->{"stderr"}
l!l&&r!l&&!r
1102450
MC/DC100%2/2
$self->{"json_log_file"} or $self->{"stderr"}
$self->{"json_log_file"} $self->{"stderr"}
Truth table100%3/3
A or B
A= $self->{"json_log_file"}B= $self->{"stderr"}
ABresult
1X1
011
000
210 50 $self->{stderr} = 1;
211 }
212  
213 184 for my $stdfile (['stderr', \*STDERR], ['stdout', \*STDOUT]) {
214 368 my ($name, $fh) = $stdfile->@*;
215 368 ▶ if ($self->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{$name}) 102 266 368
216 102 ▶ $self->{$name} = {format => $self->{$name}} if ref($self->{$name}) ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $self->{$name} ne "HASH" 102 0 102
217 # docker tends to prefer JSON
218 $self->{$name}{format} = _in_container() ? 'json' : 'text'
219 102 ▶ if (!$self->{$name}{format} || $self->{$name}{format} ne 'json' && $self->{$name}{format} ne 'text');
Branch: 2 branches
BranchTrueFalseTotal
if not $self->{$name}{"format"} or $self->{$name}{"format"} ne "json" and $self->{$name}{"format"} ne "text" 66 36 102
_in_container() ? : 42 24 66
Condition83%5/6
not $self->{$name}{"format"} or $self->{$name}{"format"} ne "json" and $self->{$name}{"format"} ne "text"
l!l&&r!l&&!r
06636
$self->{$name}{"format"} ne "json" and $self->{$name}{"format"} ne "text"
!ll&&!rl&&r
201666
MC/DC66%2/3
not $self->{$name}{"format"} or $self->{$name}{"format"} ne "json" and $self->{$name}{"format"} ne "text"
not $self->{$name}{"format"} $self->{$name}{"format"} ne "json" $self->{$name}{"format"} ne "text"
Truth table75%3/4
not(A) or B and C
A= not $self->{$name}{"format"}B= $self->{$name}{"format"} ne "json"C= $self->{$name}{"format"} ne "text"
ABCresult
1XX1
0111
00X0
0100
220 102 $self->apply_filehandle_utf8($fh);
221 102 $self->{$name}{fh} = $fh;
222 102 ▶ $self->{$name}{color} //= _fh_is_tty($fh);
Condition66%2/3
$self->{$name}{"color"} //= _fh_is_tty($fh)
l!l&&r!l&&!r
07824
MC/DC50%1/2
$self->{$name}{"color"} //= _fh_is_tty($fh)
$self->{$name}{"color"} _fh_is_tty($fh)
Truth table66%2/3
A //= B
A= $self->{$name}{"color"}B= _fh_is_tty($fh)
ABresult
1X1
011
000
223 }
224 }
225  
226 # Keep a strong reference to this, since we expect to stick around until exit anyway
227 184 $self->{code} = $self->curry::log_entry;
228 184 return $self;
229 }
230  
231 =head2 apply_filehandle_utf8
232  
233 Applies UTF-8 to filehandle if it is not utf-flavoured already
234  
235 $object->apply_filehandle_utf8($fh);
236  
237 =over 4
238  
239 =item * C<$fh> file handle
240  
241 =back
242  
243 =cut
244  
245 102 ▶sub apply_filehandle_utf8 {
Subroutine apply_filehandle_utf8: called CC=2 SCAR=6.9
Pod documented
246 102 my ($class, $fh) = @_;
247 # We'd expect `encoding(utf-8-strict)` and `utf8` if someone's already applied binmode
248 # for us, but implementation details in Perl may change those names slightly, and on
249 # some platforms (Windows?) there's also a chance of one of the UTF16LE/BE variants,
250 # so we make this check quite lax and skip binmode if there's anything even slightly
251 # utf-flavoured in the mix.
252 $fh->binmode(':encoding(UTF-8)')
253 102 ▶ unless grep { /utf/i } PerlIO::get_layers($fh, output => 1);
Branch: 1 branch
BranchTrueFalseTotal
unless grep {/utf/i;} &PerlIO::get_layers($fh, "output", 1) 43 59 102
254 102 $fh->autoflush(1);
255 }
256  
257 =head2 format_line
258  
259 Formatting the log entry with timestamp, from which the message populated,
260 severity and message.
261  
262 If color/colour param passed it adds appropriate color code for timestamp,
263 log level, from which this log message populated and actual message.
264 For non-color mode, it just returns the formatted message.
265  
266 $object->format_line($data, {color => $color});
267  
268 =over 4
269  
270 =item * C<$data> hashref - The data with stack info like package method from
271 which the message populated, timestamp, severity and message
272  
273 =item * C<$opts> hashref - the options color
274  
275 =back
276  
277 Returns only formatted string if non-color mode. Otherwise returns formatted
278 string with embedded ANSI color code using L<Term::ANSIColor>
279  
280 =cut
281  
282 18 ▶sub format_line {
Subroutine format_line: called CC=5 SCAR=16.2
Pod documented
283 18 my ($class, $data, $opts) = @_;
284  
285 # With international development teams, no matter which spelling we choose
286 # someone's going to get this wrong sooner or later... or to put another
287 # way, we got country *and* western.
288 18 ▶ $opts->{colour} = $opts->{color} || $opts->{colour};
Condition66%2/3
$opts->{'color'} || $opts->{'colour'}
l!l&&r!l&&!r
7011
MC/DC50%1/2
$opts->{'color'} || $opts->{'colour'}
$opts->{'color'} $opts->{'colour'}
Truth table66%2/3
A || B
A= $opts->{'color'}B= $opts->{'colour'}
ABresult
1X1
011
000
289  
290 # Expand formatting if necessary: it's not immediately clear how to defer
291 # handling of structured data, the ->structured method doesn't have a way
292 # to return the stringified data back to the caller for example
293 # for edge cases like `my $msg = $log->debug(...);` so we're still working
294 # on how best to handle this:
295 # https://metacpan.org/release/Log-Any/source/lib/Log/Any/Proxy.pm#L105
296 # $_ = sprintf $_->@* for grep ref, $data->{message};
297  
298 # If we have a stack entry, report the context - default to "main" if we're at top level
299 18 ▶ my $from = $data->{stack}[-1] ? join '->', @{$data->{stack}[-1]}{qw(package method)} : 'main';
Branch: 1 branch
BranchTrueFalseTotal
$data->{'stack'}[-1] ? : 18 0 18
300  
301 # Start with the plain-text details
302 my @details = (
303 Time::Moment->from_epoch($data->{epoch})->strftime('%Y-%m-%dT%H:%M:%S%3f'),
304 uc(substr $data->{severity}, 0, 1),
305 18 "[$from]", $data->{message});
306  
307 # This is good enough if we're in non-colour mode
308 18 ▶ return join ' ', @details unless $opts->{colour};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts->{"colour"} 11 7 18
309  
310 7 ▶ my @colours = ($SEVERITY_COLOUR{$data->{severity}} || die 'no severity definition found for ' . $data->{severity})->@*;
Condition50%1/2
$Log::Any::Adapter::DERIV::SEVERITY_COLOUR{$data->{'severity'}} || die('no severity definition found for ' . $data->{'severity'})
l!l
70
MC/DC0%0/1
$Log::Any::Adapter::DERIV::SEVERITY_COLOUR{$data->{'severity'}} || die('no severity definition found for ' . $data->{'severity'})
$Log::Any::Adapter::DERIV::SEVERITY_COLOUR{$data->{'severity'}}
Truth table50%1/2
A
A= $Log::Any::Adapter::DERIV::SEVERITY_COLOUR{$data->{'severity'}}
Aresult
11
00
311  
312 # Colour formatting codes applied at the start and end of each line, in case something else
313 # gets inbetween us and the output
314 7 local $Term::ANSIColor::EACHLINE = "\n";
315 7 my ($ts, $level) = splice @details, 0, 2;
316 7 $from = shift @details;
317  
318 7 return join ' ', colored($ts, qw(bright_blue)), colored($level, @colours), colored($from, qw(grey10)), map { colored($_, @colours) } @details;
319 }
320  
321 =head2 log_entry
322  
323 Add format and add color code using C<format_line> and writes the log entry
324  
325 $object->log_entry($data);
326  
327 =over 4
328  
329 =item *C<$data> hashref - The log data
330  
331 =back
332  
333 =cut
334  
335 91 ▶sub log_entry {
Subroutine log_entry: called CC=5 SCAR=16.1
Pod documented
336 91 my ($self, $data) = @_;
337 91 $data = $self->_process_data($data);
338 91 $data = $self->_process_context($data);
339 91 $data->{message} = mask_sensitive($data->{message});
340 90 my $json_data;
341 90 my %text_data = ();
342 90 ▶ my $get_json = sub { $json_data //= encode_json_text($data) . "\n"; return $json_data; };
Subroutine __ANON__: called CC=2 SCAR=6.9
Condition100%2/2
$json_data //= encode_json_text($data) . "\n"
l!l
678
MC/DC100%1/1
$json_data //= encode_json_text($data) . "\n"
$json_data
Truth table100%2/2
A
A= $json_data
Aresult
11
00
343 my $get_text =
344 90 ▶ sub { my $color = shift // 0; $text_data{$color} //= $self->format_line($data, {color => $color}) . "\n"; return $text_data{$color}; };
Subroutine __ANON__: called CC=3 SCAR=11.0
Condition100%4/4
shift() // 0
l!l
146
$text_data{$color} //= $self->format_line($data, {"color", $color}) . "\n"
l!l
218
MC/DC100%1/1
shift() // 0
shift()
MC/DC100%1/1
$text_data{$color} //= $self->format_line($data, {"color", $color}) . "\n"
$text_data{$color}
Truth table100%2/2
A
A= shift()
Aresult
11
00
Truth table100%2/2
A
A= $text_data{$color}
Aresult
11
00
345  
346 90 ▶ if ($self->{json_fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"json_fh"}) 62 28 90
347 62 _lock($self->{json_fh});
348 62 $self->{json_fh}->print($get_json->());
349 62 _unlock($self->{json_fh});
350 }
351  
352 90 for my $stdfile (qw(stderr stdout)) {
353 180 ▶ next unless $self->{$stdfile};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{$stdfile} 138 42 180
354 my $txt =
355 $self->{$stdfile}{format} eq 'json'
356 ? $get_json->()
357 42 ▶ : $get_text->($self->{$stdfile}{color});
Branch: 1 branch
BranchTrueFalseTotal
$self->{$stdfile}{'format'} eq 'json' ? : 22 20 42
358 42 my $fh = $self->{$stdfile}{fh};
359  
360 42 _lock($fh);
361 42 $fh->print($txt);
362 42 _unlock($fh);
363 }
364 }
365  
366 =head2 _process_data
367  
368 Process the data before printing out. Reduce the continues L<Future> stack
369 messages and filter the messages based on log level.
370  
371 $object->_process_data($data);
372  
373 =over 4
374  
375 =item * C<$data> hashref - The log data.
376  
377 =back
378  
379 Returns a hashref - the processed data
380  
381 =cut
382  
383 91 ▶sub _process_data {
Subroutine _process_data: called CC=1 SCAR=0.0
384 91 my ($self, $data) = @_;
385  
386 91 $data = clone($data);
387 91 $data = $self->_collapse_future_stack($data);
388 91 $data = $self->_filter_stack($data);
389  
390 91 return $data;
391 }
392  
393 =head2 _filter_stack
394  
395 Filter the stack message based on log level.
396  
397 $object->_filter_stack($data);
398  
399 =over 4
400  
401 =item * C<$data> hashref - Log stack data
402  
403 =back
404  
405 Returns hashref - the filtered data
406  
407 =cut
408  
409 91 ▶sub _filter_stack {
Subroutine _filter_stack: called CC=3 SCAR=11.0
410 91 my ($self, $data) = @_;
411  
412 91 ▶ return $data if (numeric_level($data->{severity}) <= numeric_level('warn'));
Branch: 1 branch
BranchTrueFalseTotal
if numeric_level($data->{"severity"}) <= numeric_level("warn") 79 12 91
413  
414 # now severity > warn
415 12 ▶ return $data if $self->{log_level} >= numeric_level('debug');
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"log_level"} >= numeric_level("debug") 9 3 12
416  
417 3 delete $data->{stack};
418  
419 3 return $data;
420 }
421  
422 =head2 _collapse_future_stack
423  
424 Go through the caller stack and if continuous L<Future> messages then keep
425 only one at the first.
426  
427 $object->_collapse_future_stack($data);
428  
429 =over 4
430  
431 =item * C<$data> hashref - Log stack data
432  
433 =back
434  
435 Returns a hashref - the reduced log data
436  
437 =cut
438  
439 93 ▶sub _collapse_future_stack {
Subroutine _collapse_future_stack: called CC=5 SCAR=16.1
440 93 my ($self, $data) = @_;
441 93 my $stack = $data->{stack};
442 93 my @new_stack;
443 my $previous_is_future;
444  
445 93 for my $frame ($stack->@*) {
446 218 ▶ if ($frame->{package} eq 'Future' || $frame->{package} eq 'Future::PP') {
Branch: 1 branch
BranchTrueFalseTotal
if ($frame->{'package'} eq 'Future' or $frame->{'package'} eq 'Future::PP') { } 29 189 218
Condition100%3/3
$frame->{"package"} eq "Future" or $frame->{"package"} eq "Future::PP"
l!l&&r!l&&!r
623189
MC/DC100%2/2
$frame->{"package"} eq "Future" or $frame->{"package"} eq "Future::PP"
$frame->{"package"} eq "Future" $frame->{"package"} eq "Future::PP"
Truth table100%3/3
A or B
A= $frame->{"package"} eq "Future"B= $frame->{"package"} eq "Future::PP"
ABresult
1X1
011
000
447 29 ▶ next if ($previous_is_future);
Branch: 1 branch
BranchTrueFalseTotal
if $previous_is_future 23 6 29
448 6 push @new_stack, $frame;
449 6 $previous_is_future = 1;
450 } else {
451 189 push @new_stack, $frame;
452 189 $previous_is_future = 0;
453 }
454 }
455 93 $data->{stack} = \@new_stack;
456  
457 93 return $data;
458 }
459  
460 =head2 _fh_is_tty
461  
462 Check the filehandle opened to tty
463  
464 =over 4
465  
466 =item * C<$fh> file handle
467  
468 =back
469  
470 Returns boolean
471  
472 =cut
473  
474 25 ▶sub _fh_is_tty {
Subroutine _fh_is_tty: called CC=1 SCAR=0.0
475 25 my $fh = shift;
476  
477 25 return -t $fh; ## no critic (ProhibitInteractiveTest)
478 }
479  
480 =head2 _in_container
481  
482 Returns true if we think we are currently running in a container.
483  
484 At the moment this only looks for a C<.dockerenv> file in the root directory;
485 future versions may expand this to provide a more accurate check covering
486 other container systems such as `runc`.
487  
488 Returns boolean
489  
490 =cut
491  
492 18 ▶sub _in_container {
Subroutine _in_container: called CC=1 SCAR=0.0
493 18 return -r '/.dockerenv';
494 }
495  
496 =head2 _linux_flock_data
497  
498 Based on the type of lock requested, it packs into linux binary flock structure
499 and return the string of that structure.
500  
501 Linux struct flock: "s s l l i"
502 short l_type short - Possible values: F_RDLCK(0) - read lock, F_WRLCK(1) - write lock, F_UNLCK(2) - unlock
503 short l_whence - starting offset
504 off_t l_start - relative offset
505 off_t l_len - number of consecutive bytes to lock
506 pid_t l_pid - process ID
507  
508 =over 4
509  
510 =item * C<$type> integer lock type - F_WRLCK or F_UNLCK
511  
512 =back
513  
514 Returns a string of the linux flock structure
515  
516 =cut
517  
518 120 ▶sub _linux_flock_data {
Subroutine _linux_flock_data: called CC=1 SCAR=0.0
519 120 my ($type) = @_;
520 120 my $FLOCK_STRUCT = "s s l l i";
521  
522 120 return pack($FLOCK_STRUCT, $type, SEEK_SET, 0, 0, 0);
523 }
524  
525 =head2 _flock
526  
527 call fcntl to lock or unlock a file handle
528  
529 =over 4
530  
531 =item * C<$fh> file handle
532  
533 =item * C<$type> lock type, either F_WRLCK or F_UNLCK
534  
535 =back
536  
537 Returns boolean or undef
538  
539 =cut
540  
541 # We don't use `flock` function directly here
542 # In some cases the program will do fork after the log file opened.
543 # In such case every subprocess can get lock of the log file at the same time.
544 # Using fcntl to lock a file can avoid this problem
545 120 ▶sub _flock {
Subroutine _flock: called CC=2 SCAR=7.4
546 120 my ($fh, $type) = @_;
547 120 my $lock = _linux_flock_data($type);
548 120 my $result = fcntl($fh, F_SETLKW, $lock);
549  
550 120 ▶ return $result if $result;
Branch: 1 branch
BranchTrueFalseTotal
if $result 120 0 120
551  
552 0 return undef;
553 }
554  
555 =head2 _lock
556  
557 Lock a file handler with fcntl.
558  
559 =over 4
560  
561 =item * C<$fh> File handle
562  
563 =back
564  
565 Returns boolean
566  
567 =cut
568  
569 60 ▶sub _lock {
Subroutine _lock: called CC=1 SCAR=0.0
570 60 my ($fh) = @_;
571  
572 60 return _flock($fh, F_WRLCK);
573 }
574  
575 =head2 _unlock
576  
577 Unlock a file handler locked by fcntl
578  
579 =over 4
580  
581 =item * C<$fh> File handle
582  
583 =back
584  
585 Returns boolean
586  
587 =cut
588  
589 60 ▶sub _unlock {
Subroutine _unlock: called CC=1 SCAR=0.0
590 60 my ($fh) = @_;
591  
592 60 return _flock($fh, F_UNLCK);
593 }
594  
595 =head2 level
596  
597 Return the current log level name.
598  
599 =cut
600  
601 9 ▶sub level {
Subroutine level: called CC=1 SCAR=0.0
Pod documented
602 9 my $self = shift;
603 9 return $num_to_name{$self->{log_level}};
604 }
605  
606 =head2 _process_context
607  
608 add context key value pair into data object
609  
610 =cut
611  
612 91 ▶sub _process_context {
Subroutine _process_context: called CC=2 SCAR=6.9
613 91 my ($self, $data) = @_;
614 # Iterate over the keys in $adapter_context
615 91 foreach my $key (keys %{$adapter_context}) {
616 1 $data->{$key} = $adapter_context->{$key};
617 }
618 91 return $data;
619 }
620  
621 =head2 set_context
622  
623 Set the log context hash
624  
625 =cut
626  
627 1 ▶sub set_context {
Subroutine set_context: called CC=1 SCAR=0.0
Pod documented
628 1 my ($self, $context) = @_;
629 1 $adapter_context = $context;
630 }
631  
632 =head2 clear_context
633  
634 undef the log context hash
635  
636 =cut
637  
638 1 ▶sub clear_context {
Subroutine clear_context: called CC=1 SCAR=0.0
Pod documented
639 1 my ($self) = @_;
640 1 $adapter_context = undef;
641 }
642  
643 =head2 mask_sensitive
644  
645 Mask sensitive data in the message and logs error in case of failure
646  
647 =over 4
648  
649 =item * C<$message> string - The message to be masked
650  
651 =back
652  
653 Returns string - The masked message
654  
655 =cut
656  
657 90 ▶sub mask_sensitive {
Subroutine mask_sensitive: called CC=2 SCAR=7.5
Pod documented
658 90 my ($message) = @_;
659  
660 # Define a lookup list for all sensitive data regex patterns to be logged
661  
662 90 my @sensitive_patterns = (
663 qr/\b[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}\b/i, #Email
664 qr/\b(?:token|key|oauth[ _-]?token)\s*[:=]\s*([^\s]+)/i, #Token or API key , = : value
665 qr/(?:a1|r1|ct1)-[a-z0-9]{29}/i, #OAuth, Refresh, and CTrader token patterns
666 qr/\b[a-z0-9]{15}\b/i, #API Token
667 qr/xoxb-\d+-\d+-[a-z0-9]{24,}/i, #Slack Token
668 );
669  
670 try {
671 90 foreach my $pattern (@sensitive_patterns) {
672 450 $message =~ s/$pattern/'*' x length($&)/ge;
673 }
674 90 } catch ($e) {
675 # Disable the custom warning handler temporarily to avoid potential recursion issues.
676 0 local $SIG{__WARN__} = undef;
677  
678 # Extract the error message from the exception.
679 0 chomp(my $error_msg = $e);
680  
681 # Log the error for further investigation and troubleshooting.
682 0 $log->warn("Error in mask_sensitive: $error_msg");
683 };
684  
685 90 return $message;
686 }
687  
688 7 1;
689  
690 =head1 AUTHOR
691  
692 Deriv Group Services Ltd. C<< DERIV@cpan.org >>
693  
694 =head1 LICENSE
695  
696 Copyright Deriv Group Services Ltd 2020-2021. Licensed under the same terms as Perl itself.
↑ Summary