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

filter: Statementstmt 100% 63 / 63 Branchbran 100% 16 / 16 Conditioncond 88.8% 8 / 9 MC/DCmcdc 83.3% 5 / 6 Subroutinesub 100% 12 / 12 Podpod 100% 2 / 2 totaltotal 98.1% 106 / 108 CC 13 SCAR 14.1
CC
13
Cov
99%
structured
7.0
init
6.0
__ANON__
2.0
CRAP 4.1
« blib/lib/Log/Abstraction/Backend/Object.pm ↑ Summary blib/lib/Log/Abstraction/Backend/Sendmail.pm »
1 package Log::Any::Adapter::Abstraction;
2  
3 # Route Log::Any log calls through a Log::Abstraction backend
4 9 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 9 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 9 ▶use parent 'Log::Any::Adapter::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 8 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use Log::Abstraction;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 8 our $VERSION = '0.40';
14  
15 =head1 NAME
16  
17 Log::Any::Adapter::Abstraction - Log::Any adapter backed by Log::Abstraction
18  
19 =head1 VERSION
20  
21 0.40
22  
23 =head1 SYNOPSIS
24  
25 use Log::Any::Adapter;
26 use Log::Abstraction;
27  
28 my @messages;
29  
30 # Option A: pass a pre-built Log::Abstraction instance
31 my $logger = Log::Abstraction->new(logger => \@messages, level => 'debug');
32 Log::Any::Adapter->set('Abstraction', instance => $logger);
33  
34 # Option B: let the adapter create a Log::Abstraction for you
35 Log::Any::Adapter->set('Abstraction', level => 'debug', logger => \@messages);
36  
37 # Any module that uses Log::Any will now route through Log::Abstraction
38 use Log::Any '$log';
39 $log->info('Hello world');
40  
41 =head1 DESCRIPTION
42  
43 C<Log::Any::Adapter::Abstraction> is a L<Log::Any> adapter that routes
44 messages from any module using L<Log::Any> through a L<Log::Abstraction>
45 backend. Configure a single C<Log::Abstraction> instance (with file, syslog,
46 email, array, or code-ref backends) and all C<Log::Any>-using CPAN modules
47 automatically send their output there.
48  
49 =head2 Level mapping
50  
51 Each of Log::Any's nine severity levels has a Log::Abstraction method of
52 the same name, except C<warning>:
53  
54 Log::Any level Log::Abstraction method
55 --------------- -----------------------
56 trace trace
57 debug debug
58 info info
59 notice notice
60 warning warn
61 error error
62 critical critical
63 alert alert
64 emergency emergency
65  
66 Before version 0.36, C<critical>, C<alert> and C<emergency> were all sent
67 to C<error()>.
68  
69 =head1 METHODS
70  
71 =head2 init
72  
73 Called automatically by C<Log::Any::Adapter::Base::new()>. Initialises the
74 internal C<Log::Abstraction> backend.
75  
76 =head3 Arguments (passed as key=E<gt>value pairs to C<Log::Any::Adapter-E<gt>set>)
77  
78 =over 4
79  
80 =item * C<instance>
81  
82 An existing C<Log::Abstraction> object. When supplied, the adapter wraps it
83 directly without creating a new instance. Anything other than a
84 C<Log::Abstraction> object (or subclass) is a fatal error.
85  
86 =item * Any C<Log::Abstraction-E<gt>new()> argument
87  
88 C<logger>, C<level>, C<file>, C<fd>, C<array>, C<format>, C<ctx>,
89 C<script_name>, C<verbose>, C<carp_on_warn>, C<croak_on_error>,
90 C<config_file>, C<max_messages>, C<redact>, C<timestamp_format>,
91 C<timestamp_precision>, C<utc>, C<rotate_size>, C<rotate_interval>,
92 C<rotate_keep>, C<reopen_interval>. Used to build a fresh C<Log::Abstraction>
93 instance when C<instance> is not supplied.
94  
95 =back
96  
97 =head3 Example
98  
99 Log::Any::Adapter->set('Abstraction',
100 level => 'debug',
101 format => 'json',
102 file => '/var/log/myapp.log',
103 );
104  
105 =head3 API SPECIFICATION
106  
107 =head4 Input
108  
109 {
110 instance => { type => OBJECT, isa => 'Log::Abstraction', optional => 1 },
111 logger => { optional => 1 },
112 level => { type => SCALAR, optional => 1 },
113 file => { type => SCALAR, optional => 1 },
114 fd => { optional => 1 },
115 array => { type => ARRAYREF, optional => 1 },
116 format => { type => SCALAR, optional => 1 },
117 ctx => { optional => 1 },
118 script_name => { type => SCALAR, optional => 1 },
119 verbose => { type => BOOLEAN, optional => 1 },
120 carp_on_warn => { type => BOOLEAN, optional => 1 },
121 croak_on_error => { type => BOOLEAN, optional => 1 },
122 config_file => { type => SCALAR, optional => 1 },
123 max_messages => { type => INTEGER, min => 0, optional => 1 },
124 redact => { optional => 1 },
125 timestamp_format => { type => SCALAR, optional => 1 },
126 timestamp_precision => { type => INTEGER, min => 0, max => 9, optional => 1 },
127 utc => { type => BOOLEAN, optional => 1 },
128 rotate_size => { type => SCALAR, optional => 1 },
129 rotate_interval => { type => SCALAR, optional => 1 },
130 rotate_keep => { type => INTEGER, min => 0, optional => 1 },
131 reopen_interval => { type => INTEGER, min => -1, optional => 1 },
132 }
133  
134 =head4 Output
135  
136 { type => 'object', class => 'Log::Any::Adapter::Abstraction' }
137  
138 =head3 MESSAGES
139  
140 Error Meaning / Action
141 ---------------------------------------- -----------------------------------------
142 "...: instance must be a Log::Abstraction 'instance' was given something other
143 object" than a Log::Abstraction object.
144 (any Log::Abstraction croak) The supplied constructor args are invalid.
145 See Log::Abstraction for detail.
146  
147 =cut
148  
149 # ---------------------------------------------------------------------------
150 # Map Log::Any level names to Log::Abstraction method names, which are also
151 # its level names (for the is_* threshold checks). Only 'warning' differs.
152 # ---------------------------------------------------------------------------
153 8 my %LA_TO_METHOD = (
154 trace => 'trace',
155 debug => 'debug',
156 info => 'info',
157 notice => 'notice',
158 warning => 'warn',
159 error => 'error',
160 critical => 'critical',
161 alert => 'alert',
162 emergency => 'emergency',
163 );
164  
165 # ---------------------------------------------------------------------------
166 # init -- create or store the Log::Abstraction instance backing this adapter
167 #
168 # Purpose: Called by Log::Any::Adapter::Base::new() after blessing the
169 # adapter hash. Either wraps an existing Log::Abstraction object
170 # (from the 'instance' key) or builds a new one from the remaining
171 # adapter constructor arguments.
172 # Entry: $self -- adapter hash blessed into this class.
173 # Exit: Sets $self->{_logger}; returns nothing.
174 # Side effects: May construct a Log::Abstraction object (which may open
175 # file handles, start syslog, etc.).
176 # ---------------------------------------------------------------------------
177 156 ▶sub init {
Subroutine init: called CC=6 SCAR=17.9
Pod documented
178 156 my $self = shift;
179  
180 # Reuse a caller-supplied Log::Abstraction instance if one was provided;
181 # anything else is a mistake, not a request for a default logger
182 156 ▶ if(defined(my $inst = $self->{instance})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $inst = $self->{"instance"})) 95 61 156
183 95 ▶ if(!Scalar::Util::blessed($inst) || !$inst->isa('Log::Abstraction')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($inst) and $inst->isa("Log::Abstraction")) 2 93 95
Condition100%3/3
builtin::blessed($inst) and $inst->isa("Log::Abstraction")
!ll&&!rl&&r
1193
MC/DC100%2/2
builtin::blessed($inst) and $inst->isa("Log::Abstraction")
builtin::blessed($inst) $inst->isa("Log::Abstraction")
Truth table100%3/3
A and B
A= builtin::blessed($inst)B= $inst->isa("Log::Abstraction")
ABresult
0X0
100
111
184 2 Carp::croak(__PACKAGE__, ': instance must be a Log::Abstraction object');
185 }
186 93 $self->{_logger} = $inst;
187 93 return;
188 }
189  
190 # Build a fresh Log::Abstraction from the constructor key=value pairs
191 61 my %new_args;
192 61 for my $key (qw(
193 logger level file fd array format ctx script_name verbose
194 carp_on_warn croak_on_error config_file max_messages redact
195 timestamp_format timestamp_precision utc
196 rotate_size rotate_interval rotate_keep reopen_interval
197 )) {
198 1281 ▶ $new_args{$key} = $self->{$key} if exists $self->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{$key} 260 1021 1281
199 }
200 61 $self->{_logger} = Log::Abstraction->new(%new_args);
201 }
202  
203 =head2 Logging methods
204  
205 =over 4
206  
207 =item trace
208  
209 =item debug
210  
211 =item info
212  
213 =item notice
214  
215 =item warning
216  
217 =item error
218  
219 =item critical
220  
221 =item alert
222  
223 =item emergency
224  
225 =back
226  
227 $adapter->info($message);
228  
229 Called by L<Log::Any> with the formatted message; each sends it to the
230 matching L<Log::Abstraction> method (see L</Level mapping>). These methods
231 are generated when the module loads. A croak from Log::Abstraction (e.g.
232 C<croak_on_error>) is turned into a C<Carp::carp>, so logging never dies.
233  
234 =head3 API SPECIFICATION
235  
236 =head4 Input
237  
238 { message => { type => 'string' } }
239  
240 =head4 Output
241  
242 { type => 'undef' }
243  
244 =head2 structured
245  
246 $adapter->structured($level, $category, @parts, \%fields);
247  
248 Called by L<Log::Any> in place of the logging methods, with the message
249 parts and, when there are any, a final hashref of structured fields: the
250 proxy's C<context> merged with a hashref passed as the last argument of the
251 log call. The parts are joined with a space and sent, with the fields, to
252 the matching L<Log::Abstraction> method, so
253  
254 $log->info('login', { user_id => 42 });
255  
256 reaches Log::Abstraction as C<info('login', { user_id =E<gt> 42 })>. See
257 L<Log::Abstraction/Structured fields> for where the fields go. As with the
258 logging methods, a croak is turned into a C<Carp::carp>.
259  
260 =head3 API SPECIFICATION
261  
262 =head4 Input
263  
264 {
265 level => { type => 'string' },
266 category => { type => 'string' },
267 parts => { type => 'array' },
268 fields => { type => 'hashref', optional => 1 },
269 }
270  
271 =head4 Output
272  
273 { type => 'undef' }
274  
275 =head2 Detection methods
276  
277 =over 4
278  
279 =item is_trace
280  
281 =item is_debug
282  
283 =item is_info
284  
285 =item is_notice
286  
287 =item is_warning
288  
289 =item is_error
290  
291 =item is_critical
292  
293 =item is_alert
294  
295 =item is_emergency
296  
297 =back
298  
299 if($adapter->is_debug()) { ... }
300  
301 Return 1 if a message at that level would be logged by the wrapped
302 L<Log::Abstraction> instance's level threshold, otherwise 0. Each calls the
303 L<Log::Abstraction> method of the same name (C<is_warning> calls
304 C<is_warn>). As in Log::Abstraction, C<is_trace> equals C<is_debug>.
305  
306 =head3 API SPECIFICATION
307  
308 =head4 Input
309  
310 {} (no arguments)
311  
312 =head4 Output
313  
314 { type => 'boolean' }
315  
316 =cut
317  
318 # ---------------------------------------------------------------------------
319 # Build logging methods for every Log::Any level name.
320 # Each method delegates to the corresponding Log::Abstraction dispatch method.
321 # Logging through Log::Any must never kill the module doing the logging, so
322 # a croak from Log::Abstraction (e.g. croak_on_error) is turned into a carp.
323 # ---------------------------------------------------------------------------
324 8 for my $la_level (keys %LA_TO_METHOD) {
325 72 my $method = $LA_TO_METHOD{$la_level};
326 8 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
327 72 ▶ *{$la_level} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
328 10 my ($self, $msg) = @_;
329 # The eval would otherwise reset the calling module's $@
330 10 local ($@, $!);
331 10 ▶ eval { $self->{_logger}->$method($msg); 1 } or Carp::carp($@);
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->{"_logger"}->$method($msg); 1 } } or Carp::carp($@) 9 1 10
332 10 return;
333 72 };
334 }
335  
336 # ---------------------------------------------------------------------------
337 # structured -- receive a log call with its structured fields from Log::Any
338 #
339 # Purpose: Log::Any calls this instead of the per-level methods when the
340 # adapter can('structured'), passing the parts as given and the
341 # merged context and fields as a final hashref (only when there are
342 # any), so the fields reach Log::Abstraction as data, not text.
343 # Entry: $self -- the adapter.
344 # $level -- a Log::Any level name.
345 # $category -- the Log::Any category (unused).
346 # @parts -- message parts, then optionally a hashref of fields.
347 # Exit: Returns nothing.
348 # Side effects: Logs through the wrapped Log::Abstraction instance.
349 # ---------------------------------------------------------------------------
350 39 ▶sub structured {
Subroutine structured: called CC=7 SCAR=19.5
Pod documented
351 39 my ($self, $level, $category, @parts) = @_;
352  
353 39 ▶ my $fields = (@parts && (ref($parts[-1]) eq 'HASH')) ? pop(@parts) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@parts && ref $parts[-1] eq 'HASH' ? : 6 33 39
Condition66%2/3
@parts and ref $parts[-1] eq "HASH"
!ll&&!rl&&r
0336
MC/DC50%1/2
@parts and ref $parts[-1] eq "HASH"
@parts ref $parts[-1] eq "HASH"
Truth table66%2/3
A and B
A= @partsB= ref $parts[-1] eq "HASH"
ABresult
0X0
100
111
354 39 ▶ my $msg = join(' ', grep { defined($_) && length($_) } @parts);
Condition100%3/3
defined $_ && length $_
!ll&&!rl&&r
1141
MC/DC100%2/2
defined $_ && length $_
defined $_ length $_
Truth table100%3/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
355 39 ▶ my $method = $LA_TO_METHOD{$level} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $method = $LA_TO_METHOD{$level} or return 38 1 39
356  
357 # The eval would otherwise reset the calling module's $@
358 38 local ($@, $!);
359 38 ▶ eval { $self->{_logger}->$method($msg, ($fields ? $fields : ())); 1 } or Carp::carp($@);
Branch: 2 branches
BranchTrueFalseTotal
eval { do { $self->{"_logger"}->$method($msg, $fields ? $fields : ()); 1 } } or Carp::carp($@) 37 1 38
$fields ? : 6 32 38
360 38 return;
361 }
362  
363 # ---------------------------------------------------------------------------
364 # Build is_* detection methods for every Log::Any level name.
365 # Each delegates to the matching Log::Abstraction is_* method (is_warning to
366 # is_warn), which returns 1 when messages at that level would not be dropped.
367 # ---------------------------------------------------------------------------
368 8 for my $la_level (keys %LA_TO_METHOD) {
369 72 my $detector = "is_$LA_TO_METHOD{$la_level}";
370 8 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
371 72 ▶ *{"is_$la_level"} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
372 58 my $self = $_[0];
373 58 return $self->{_logger}->$detector();
374 72 };
375 }
376  
377 =head1 LIMITATIONS
378  
379 =over 4
380  
381 =item B<Message parts are joined with a space>
382  
383 In structured mode Log::Any passes the message parts, including any
384 C<prefix>, separately; L</structured> joins them with a single space, so
385 a prefix is followed by a space.
386  
387 =item B<Filters disable structured fields>
388  
389 Log::Any doesn't use L</structured> when the proxy has a C<filter>; the
390 fields then arrive as text appended to the message, as Log::Any formats them.
391  
392 =item B<Logging never dies>
393  
394 A croak from the wrapped C<Log::Abstraction> instance, such as from
395 C<croak_on_error>, is turned into a C<Carp::carp> so that a module logging
396 through Log::Any is never killed by its log call.
397  
398 =item B<Log::Any as optional, not required>
399  
400 This adapter requires L<Log::Any> at runtime, but Log::Any is listed as a
401 C<recommends> dependency rather than C<requires>. CPAN clients that do not
402 install recommended modules will allow this adapter to be installed but not
403 loaded. Install Log::Any explicitly if you intend to use this adapter.
404  
405 =back
406  
407 =head1 AUTHOR
408  
409 Nigel Horne C<njh@nigelhorne.com>
410  
411 =head1 SEE ALSO
412  
413 L<Log::Abstraction>, L<Log::Any>, L<Log::Any::Adapter>
414  
415 =encoding utf-8
416  
417 =head1 FORMAL SPECIFICATION
418  
419 =head2 init
420 ┌─ AdapterState ──────────────────────────────────────────────
421 │ _logger : Log::Abstraction
422 └─────────────────────────────────────────────────────────────
423  
424 ┌─ Init ──────────────────────────────────────────────────────
425 │ args? : { instance? : Log::Abstraction | logger_args }
426 │ result! : AdapterState
427 ├─────────────────────────────────────────────────────────────
428 │ args?.instance ≠ ∅ ∧ isa(args?.instance, Log::Abstraction)
429 │ ⟹ result!._logger = args?.instance
430 │ args?.instance = ∅
431 │ ⟹ result!._logger = Log::Abstraction::new(logger_args)
432 └─────────────────────────────────────────────────────────────
433  
434 =head1 COPYRIGHT AND LICENSE
435  
436 Copyright (C) 2026 Nigel Horne
437  
438 Usage is subject to the GPL2 licence terms.
439 If you use it,
440 please let me know.
441  
442 =cut
443  
444 8 1;
« blib/lib/Log/Abstraction/Backend/Object.pm ↑ Summary blib/lib/Log/Abstraction/Backend/Sendmail.pm »