blib/lib/Log/Abstraction.pm

filter: Statementstmt 98.6% 816 / 827 Branchbran 94.7% 377 / 398 Conditioncond 81.8% 225 / 275 MC/DCmcdc 60.4% 98 / 162 Subroutinesub 100% 113 / 113 Podpod 100% 15 / 15 totaltotal 91.8% 1644 / 1790 CC 305 SCAR 28.4
CC
305
Cov
95%
new
56.0
_log
29.3
_send_email
28.3
CRAP 17.1
↑ Summary blib/lib/Log/Abstraction/Backend/Journald.pm »
1 package Log::Abstraction;
2  
3 # TODO: OpenTelemetry (OTel) Logs backend β€” not yet implemented.
4 #
5 # The goal is to route log messages to an OTel collector via
6 # OpenTelemetry::Logs::Logger->emit_record(), allowing Log::Abstraction
7 # to participate in a unified traces+logs+metrics pipeline.
8 #
9 # Why it is blocked (last assessed 2026-07-10, OTel Perl v0.033):
10 #
11 # 1. emit_record() is a no-op stub. OpenTelemetry::Logs::Logger
12 # contains "method emit_record ( %args ) { }" β€” every call is
13 # silently discarded. This has been the case since logs were added
14 # as "experimental" in v0.023 (June 2024).
15 #
16 # 2. The SDK has no Logs implementation at all. SDK::Trace::* is
17 # complete (providers, processors, samplers, OTLP exporter), but
18 # there is no SDK::Logs::LogRecord, no Batch/Simple processor, and
19 # no SDK::Logs::LoggerProvider. OpenTelemetry::Exporter::OTLP::Logs
20 # exists as a module but has no processor pipeline to feed it.
21 #
22 # 3. The official Log::Any::Adapter::OpenTelemetry has a documented
23 # FIXME: it cannot safely cache the Logger at construction time,
24 # because acquiring a Logger before a real LoggerProvider is
25 # registered returns a no-op that can never be upgraded. This is
26 # an unresolved architectural issue upstream.
27 #
28 # 4. is_debug() / is_* detection in the OTel adapter reads
29 # otel_config('LOG_LEVEL'), which is the SDK's own internal
30 # diagnostic level, not the application log level β€” a semantic bug
31 # that would propagate into any adapter we write on top.
32 #
33 # 5. The Logs stack depends on Object::Pad (Corinna), adding a
34 # non-trivial dependency and Perl >= 5.26 requirement in practice.
35 #
36 # When to revisit: watch for OpenTelemetry::SDK::Logs::LogRecord::Processor
37 # appearing on CPAN. That signals the end-to-end SDK pipe is functional.
38 # Estimated: late 2026, based on the Trace SDK timeline (~6-9 months after
39 # the Trace API stabilised).
40 #
41 # Implementation sketch (for when the above blockers are resolved):
42 # - Add an 'opentelemetry' sub-key to the HASH logger backend.
43 # - In _log: call otel_logger_provider()->logger()->emit_record(
44 # timestamp => Time::HiRes::time(),
45 # severity_text => $level,
46 # severity_number => $OTEL_SEVERITY{$level},
47 # body => $str,
48 # attributes => $self->{ctx} ? { ctx => $self->{ctx} } : {},
49 # );
50 # - Map internal levels: trace=1, debug=5, info=9, notice=10,
51 # warn=13, error=17 (OTel SeverityNumber spec, table 5).
52 # - Store the provider reference, not a cached Logger, to survive
53 # provider swaps (workaround for blocker 3 above).
54  
55 # Enforce strict variable declarations and enable common warnings
56 44 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
57 44 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 # Automatically throw exceptions on failed built-ins (open, close, socket,
60 # send...). Not ':all': that adds system()/exec(), which this module never
61 # calls, and which would make IPC::System::Simple a hidden dependency
62 44 ▶use autodie qw(:default);
Subroutine BEGIN: called CC=1 SCAR=0.0
63  
64 # Core and CPAN dependencies. Functions are called by their full names
65 # and nothing is imported, so that they can't be called as methods on a
66 # logger ($log->croak, $log->syslog ...). Readonly::Values::Syslog only
67 # exports variables (%syslog_values, $DEBUG ...)
68 44 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
69 44 ▶use IO::Handle ();
Subroutine BEGIN: called CC=1 SCAR=0.0
70 44 ▶use Config::Abstraction 0.40;
Subroutine BEGIN: called CC=1 SCAR=0.0
71 44 ▶use Params::Get 0.15;
Subroutine BEGIN: called CC=1 SCAR=0.0
72 44 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
73 44 ▶use Readonly ();
Subroutine BEGIN: called CC=1 SCAR=0.0
74 44 ▶use Readonly::Values::Syslog 0.04;
Subroutine BEGIN: called CC=1 SCAR=0.0
75 43 ▶use Return::Set 0.04;
Subroutine BEGIN: called CC=1 SCAR=0.0
76 43 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
77 43 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
78 43 ▶use Time::Local ();
Subroutine BEGIN: called CC=1 SCAR=0.0
79  
80 # Sub::Private in enforce mode: _-prefixed subs decorated :Private croak when
81 # called from outside this package. HARNESS_ACTIVE bypasses checks during
82 # make test so white-box tests can still reach private methods. 0.06 also
83 # enforces when this module is loaded at run time (require, Log::Any). The
84 # mode is set for this package only (0.07), not in $Sub::Private::config,
85 # which would change it for every other module using Sub::Private.
86 43 ▶use Sub::Private 0.07 { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
87  
88 # The backends, one object per destination, built by new() (see
89 # _build_backends). Loaded now rather than on demand, so that they are
90 # compiled with the rest of the module
91 42 ▶use Log::Abstraction::Backend;
Subroutine BEGIN: called CC=1 SCAR=0.0
92 42 ▶use Log::Abstraction::Backend::Array;
Subroutine BEGIN: called CC=1 SCAR=0.0
93 42 ▶use Log::Abstraction::Backend::Code;
Subroutine BEGIN: called CC=1 SCAR=0.0
94 42 ▶use Log::Abstraction::Backend::Fd;
Subroutine BEGIN: called CC=1 SCAR=0.0
95 42 ▶use Log::Abstraction::Backend::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
96 42 ▶use Log::Abstraction::Backend::Journald;
Subroutine BEGIN: called CC=1 SCAR=0.0
97 42 ▶use Log::Abstraction::Backend::LogAny;
Subroutine BEGIN: called CC=1 SCAR=0.0
98 42 ▶use Log::Abstraction::Backend::LogDispatch;
Subroutine BEGIN: called CC=1 SCAR=0.0
99 42 ▶use Log::Abstraction::Backend::Object;
Subroutine BEGIN: called CC=1 SCAR=0.0
100 42 ▶use Log::Abstraction::Backend::Sendmail;
Subroutine BEGIN: called CC=1 SCAR=0.0
101 42 ▶use Log::Abstraction::Backend::Syslog;
Subroutine BEGIN: called CC=1 SCAR=0.0
102  
103 # ---------------------------------------------------------------------------
104 # Module-level constants -- no magic strings or numbers anywhere below
105 # ---------------------------------------------------------------------------
106  
107 # Default minimum log level when none is specified in new()
108 42 Readonly::Scalar my $DEFAULT_LEVEL => 'warning';
109  
110 # Default SMTP delivery parameters for the sendmail backend
111 42 Readonly::Scalar my $DEFAULT_SMTP_HOST => 'localhost';
112 42 Readonly::Scalar my $DEFAULT_SMTP_PORT => 25;
113 42 Readonly::Scalar my $DEFAULT_FROM_ADDR => 'noreply@localhost';
114 42 Readonly::Scalar my $MIN_PORT => 1;
115 42 Readonly::Scalar my $MAX_PORT => 65535;
116  
117 # Default strftime pattern for %timestamp% and the JSON timestamp
118 42 Readonly::Scalar my $DEFAULT_TIMESTAMP_FORMAT => '%Y-%m-%d %H:%M:%S';
119  
120 # strftime pattern for timestamp_format => 'iso8601' or 'rfc3339', without
121 # the offset, which is 'Z' in UTC and '%:z' otherwise
122 42 Readonly::Scalar my $RFC3339_TIMESTAMP_FORMAT => '%Y-%m-%dT%H:%M:%S';
123  
124 # Most digits of fractional seconds (nanoseconds); a %N without a width
125 # gives this many
126 42 Readonly::Scalar my $MAX_TIMESTAMP_PRECISION => 9;
127  
128 # Number of rotated files kept (FILE.1 ... FILE.5) when rotate_keep isn't given
129 42 Readonly::Scalar my $DEFAULT_ROTATE_KEEP => 5;
130  
131 # Seconds after which an open log file is closed and opened again, when
132 # reopen_interval isn't given, in case a rotation tool doesn't send SIGHUP
133 42 Readonly::Scalar my $DEFAULT_REOPEN_INTERVAL => 300;
134  
135 # reopen_interval values that aren't a number of seconds
136 42 Readonly::Scalar my $REOPEN_EVERY_WRITE => 0; # close after every line
137 42 Readonly::Scalar my $REOPEN_ON_SIGHUP => -1; # only when told to
138  
139 # Multipliers for the K/M/G suffixes of rotate_size
140 42 Readonly::Hash my %SIZE_UNITS => (
141 '' => 1,
142 'k' => 1024,
143 'm' => 1024 ** 2,
144 'g' => 1024 ** 3,
145 );
146  
147 # rotate_interval names, each mapped to a function of (epoch seconds, UTC
148 # offset in seconds, use UTC?) that returns the period it falls in. The file
149 # rotates when its last-modified time is in an earlier period than now.
150 # Weeks start on Monday: day 0 (1970-01-01) was a Thursday
151 Readonly::Hash my %ROTATE_PERIOD => (
152 4 ▶ hourly => sub { int(($_[0] + $_[1]) / 3600) },
Subroutine __ANON__: called CC=1 SCAR=0.0
153 12 ▶ daily => sub { int(($_[0] + $_[1]) / 86_400) },
Subroutine __ANON__: called CC=1 SCAR=0.0
154 4 ▶ weekly => sub { int((int(($_[0] + $_[1]) / 86_400) + 3) / 7) },
Subroutine __ANON__: called CC=1 SCAR=0.0
155 4 ▶ monthly => sub { my @tm = $_[2] ? gmtime($_[0]) : localtime($_[0]); ($tm[5] * 12) + $tm[4] },
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
$_[2] ? : 0 4 4
156 42 );
157  
158 # Default log-line format tokens for file/fd/scalar-path backends
159 42 Readonly::Scalar my $DEFAULT_FORMAT => '%level%> [%timestamp%] %class% %callstack% %message%';
160 42 Readonly::Scalar my $DEFAULT_FORMAT_NOCLASS => '%level%> [%timestamp%] %callstack% %message%';
161  
162 # The backend class for each key of a logger hash, in the order they are
163 # given a message
164 42 Readonly::Array my @HASH_BACKENDS => qw(file array sendmail syslog journald log_any log_dispatch fd);
165 42 Readonly::Hash my %BACKEND_CLASS => (
166 array => 'Log::Abstraction::Backend::Array',
167 fd => 'Log::Abstraction::Backend::Fd',
168 file => 'Log::Abstraction::Backend::File',
169 journald => 'Log::Abstraction::Backend::Journald',
170 log_any => 'Log::Abstraction::Backend::LogAny',
171 log_dispatch => 'Log::Abstraction::Backend::LogDispatch',
172 sendmail => 'Log::Abstraction::Backend::Sendmail',
173 syslog => 'Log::Abstraction::Backend::Syslog',
174 );
175  
176 # Regex: characters forbidden in a log-file path (prevents command injection).
177 # Anchored with \z, not $, which would accept a trailing newline
178 42 Readonly::Scalar my $RE_SAFE_PATH => qr/^([^<>|*?;!`\$"\x00-\x1F]+)\z/;
179  
180 # Regex: path component that would escape the intended directory
181 42 Readonly::Scalar my $RE_DOTDOT => qr/\.\./;
182  
183 # Regex: characters forbidden in an SMTP hostname (allows a-z, A-Z, 0-9, dot, hyphen)
184 42 Readonly::Scalar my $RE_SAFE_HOST => qr/[^a-zA-Z0-9.\-]/;
185  
186 # Regex: a valid TCP port number string (decimal digits only; range checked separately)
187 42 Readonly::Scalar my $RE_PORT => qr/^\d+$/;
188  
189 # Regex: a valid journald field name (uppercase ASCII, digits and underscore,
190 # not starting with an underscore, which journald reserves for trusted fields)
191 42 Readonly::Scalar my $RE_JOURNALD_FIELD => qr/^[A-Z0-9][A-Z0-9_]*$/;
192  
193 # Most messages a sendmail digest holds, unless digest_max says otherwise;
194 # beyond it they are only counted
195 42 Readonly::Scalar my $DEFAULT_DIGEST_MAX => 100;
196  
197 # Exit status of an async sendmail child (see _send_email)
198 42 Readonly::Scalar my $EXIT_SENT => 0;
199 42 Readonly::Scalar my $EXIT_FAILED => 1;
200  
201 # What each match of a redact pattern is replaced with
202 42 Readonly::Scalar my $REDACTED_MARKER => '[REDACTED]';
203  
204 # Single JSON encoder for format => 'json', built on first use. It returns
205 # a character string so that all backends share one output-encoding path
206 42 my $json_encoder;
207  
208 # How many SIGHUP signals the process has had. Each open log file remembers the
209 # count when it was opened, and is opened again on the next write once the
210 # count has changed. The handler only counts: closing a handle there could
211 # close it between _file_handle returning it and the print
212 42 my $sighup_count = 0;
213  
214 # The SIGHUP handler that _catch_sighup installed, if it is installed; the
215 # $SIG{HUP} it replaced, put back by _release_sighup; and how many loggers
216 # use it (each has _sighup set)
217 42 my $sighup_handler;
218 my $sighup_previous;
219 42 my $sighup_users = 0;
220  
221 # Process IDs of the children sending emails for sendmail's async option,
222 # not yet reaped (by _reap_email_children)
223 42 my @email_children;
224  
225 =head1 NAME
226  
227 Log::Abstraction - Logging Abstraction Layer
228  
229 =head1 VERSION
230  
231 0.41
232  
233 =cut
234  
235 42 our $VERSION = '0.41';
236  
237 =head1 SYNOPSIS
238  
239 use Log::Abstraction;
240  
241 # The default level is 'warning'; 'trace' lets every example through
242 my $logger = Log::Abstraction->new(logger => 'logfile.log', level => 'trace');
243  
244 $logger->debug('This is a debug message');
245 $logger->info('This is an info message');
246 $logger->notice('This is a notice message');
247 $logger->trace('This is a trace message');
248 $logger->warn({ warning => 'This is a warning message' });
249  
250 # Structured fields
251 $logger->info('User logged in', { user_id => 42 });
252  
253 =head1 DESCRIPTION
254  
255 The C<Log::Abstraction> class provides a flexible logging layer on top of
256 different types of loggers, including code references, arrays, file paths,
257 and objects. It also supports logging to syslog if configured.
258  
259 =head2 Unicode
260  
261 Messages may be character strings containing any Unicode text. The file,
262 fd and scalar-path backends write character strings as UTF-8 (unless an
263 C<fd> handle already has a C<:utf8> or C<:encoding> layer, in which case the
264 handle does the encoding), and C<format =E<gt> 'json'> output is UTF-8 too.
265 journald fields are sent as UTF-8. Byte strings are written unchanged.
266  
267 =head2 Structured fields
268  
269 Every logging method accepts a hash reference of structured fields after
270 the message:
271  
272 $logger->info('User logged in', { user_id => 42, ip => $ip });
273 $logger->warn('Slow query', { ms => 1250 });
274  
275 A hash reference is taken as fields only when it is the last of two or more
276 arguments, so C<warn({ warning =E<gt> ... })> keeps its meaning, and a lone
277 hash reference is still a message. An empty hash reference is ignored. The
278 fields are copied, so changing the hash afterwards doesn't change what was
279 logged. They are kept out of the message and go to each backend as follows:
280  
281 =over 4
282  
283 =item * L</messages>, C<array> and an ARRAY C<logger> -- a C<fields> key in
284 the entry, alongside C<level> and C<message>.
285  
286 =item * a CODE C<logger> -- a C<fields> key in the hashref it is called with.
287  
288 =item * C<format =E<gt> 'json'> -- a nested C<fields> object. Objects are
289 stringified; other references are kept as JSON data.
290  
291 =item * C<journald> -- journal fields. Each name is upper-cased, characters
292 other than C<A-Z>, C<0-9> and C<_> become C<_>, leading underscores are
293 removed and it is cut to 64 characters; a field left with no name is
294 dropped. Fields override the extra keys in the C<journald> hash, but never
295 C<MESSAGE>, C<PRIORITY> or C<SYSLOG_IDENTIFIER>.
296  
297 =item * text formats (C<file>, C<fd>, a scalar C<logger>), C<syslog>,
298 C<sendmail> and object loggers -- appended to the message as logfmt-style
299 C<key=value> pairs in key order, e.g. C<User logged in ip=10.0.0.1 user_id=42>.
300 Characters other than C<[\w.-]> in a key become C<_>. A value that is empty
301 or contains white space, C<">, C<=> or C<\> is double-quoted, with C<"> and
302 C<\> escaped and control characters written as C<\n>, C<\r>, C<\t> or
303 C<\xNN>. Objects are stringified and other references written as JSON. An
304 object logger is passed the pairs as an extra argument after the message.
305  
306 =back
307  
308 When logging through L<Log::Any>, a hash reference at the end of the call,
309 together with the proxy's C<context>, arrives here as fields; see
310 L<Log::Any::Adapter::Abstraction/structured>.
311  
312 =head2 Redaction
313  
314 The C<redact> option removes secrets before a message reaches the history
315 or any backend. Each match of any of its patterns is replaced with
316 C<[REDACTED]>:
317  
318 my $log = Log::Abstraction->new(
319 logger => '/var/log/myapp.log',
320 redact => [qr/password=\S+/, qr/\b\d{4}(?:[ -]?\d{4}){3}\b/],
321 );
322 $log->warn('Login failed: user=fred password=hunter2');
323 # Login failed: user=fred [REDACTED]
324  
325 To keep the start of a match, end it with C<\K>: C<qr/password=\K\S+/> logs
326 C<password=[REDACTED]>. The patterns run over the whole message, after its
327 arguments are joined, so a match may span them, as in
328 C<$log-E<gt>info('password=', $password)>; a CODE or object logger then gets
329 the joined message as one argument. The text given to C<carp> or C<croak>
330 (see L</warn> and L</error>) is redacted too.
331  
332 L</Structured fields> are redacted as well: string values, including those
333 inside plain hashes and arrays, and objects whose stringification matches
334 (they become the redacted string). Field names aren't redacted, nor are
335 the format string, C<%env_*%> values or C<ctx>.
336  
337 Redaction is applied only to messages that pass the logger's C<level>, so
338 it costs nothing for messages that are dropped. A pattern that can match
339 the empty string, such as C<qr/x*/>, is rejected by L</new>.
340  
341 =head2 Email digests
342  
343 C<min_interval> limits the C<sendmail> backend to one email per interval,
344 dropping the messages in between. With C<digest>, they are held instead,
345 and sent ahead of the next message in the first email after the interval:
346  
347 my $log = Log::Abstraction->new(
348 logger => {
349 file => '/var/log/myapp.log',
350 sendmail => {
351 to => 'ops@example.com',
352 level => 'error',
353 min_interval => 300,
354 digest => 1,
355 format => '%level%> [%timestamp%] %message%',
356 },
357 },
358 );
359  
360 Each message is one line of the email, oldest first, as its own email body
361 would be: formatted with the C<sendmail> C<format> if there is one (as
362 above, so that each line has its time), else the message. At most
363 C<digest_max> messages (default 100) are held; later ones are only
364 counted, and the email says C<... and N more messages> after the held ones.
365 Messages held when an email fails to send stay held, and the new one is
366 held with them.
367  
368 Nothing is sent on a timer: held messages go out with the next email,
369 when L</flush> is called, or when the logger is destroyed (which calls
370 L</flush>). A clone made with L</new> starts with none held.
371  
372 =head2 Per-backend level and format
373  
374 Every backend can have its own C<level> and C<format>, as well as the
375 logger's. C<syslog>, C<journald> and C<sendmail> are hashes already, so
376 they take them as keys. C<file>, C<fd> and C<array>, inside a C<logger> hash
377 or at the top level, and C<log_any> and C<log_dispatch>, may be given as a
378 hash holding the destination under the backend's own name:
379  
380 my $log = Log::Abstraction->new(
381 level => 'debug',
382 logger => {
383 file => { file => '/var/log/myapp.log', format => 'json' },
384 fd => { fd => \*STDERR, level => 'warning' },
385 array => { array => \@recent, level => 'info' },
386 syslog => { level => 'error', format => '%level%: %message%' },
387 },
388 );
389  
390 =over 4
391  
392 =item * C<level> -- the backend only gets messages at this level or more
393 severe. A level name or a syslog number (0-7). The logger's C<level> is
394 applied first, so a backend's level can only narrow it: set the logger's
395 C<level> to the most verbose any backend wants.
396  
397 =item * C<format> -- a format string, or C<json>, as for the logger's
398 L</format>, which it overrides. For C<file> and C<fd> it is the line
399 written. For the others, which by default get the message as it is, it
400 replaces the message: the C<array> entry's C<message>, the text sent to
401 syslog, Log::Any or Log::Dispatch, the journal's C<MESSAGE> field and the
402 email body.
403  
404 =back
405  
406 The plain forms (C<file =E<gt> $path>, C<fd =E<gt> $handle>,
407 C<array =E<gt> \@array>, C<log_any =E<gt> $category>,
408 C<log_dispatch =E<gt> $dispatcher>) still work and have no level or format of their
409 own. A blessed handle object is a destination, not the hash form.
410  
411 =head2 Forwarding to Log::Any and Log::Dispatch
412  
413 L<Log::Any::Adapter::Abstraction> brings messages from L<Log::Any> into
414 C<Log::Abstraction>. The C<log_any> and C<log_dispatch> backends go the
415 other way, sending messages on to an application's existing L<Log::Any> or
416 L<Log::Dispatch> set-up, alongside any other backends:
417  
418 my $log = Log::Abstraction->new(
419 level => 'debug',
420 logger => {
421 log_any => 'MyApp', # a category, or a Log::Any logger
422 log_dispatch => $dispatcher, # a Log::Dispatch object
423 file => '/var/log/myapp.log',
424 },
425 );
426  
427 Levels keep their names, except that C<warn> becomes C<warning>, and
428 Log::Dispatch, which has nothing below C<debug>, gets C<trace> messages as
429 C<debug>. Log::Any gets L</Structured fields> as its trailing hashref, so a
430 structured adapter receives them as data; Log::Dispatch has no fields, so
431 they are appended to the message as text. With its own C<format> (see
432 L</Per-backend level and format>) a backend gets the formatted line instead.
433  
434 A C<Log::Any> category name is looked up with
435 C<Log::Any-E<gt>get_logger(category =E<gt> $name)> (which needs L<Log::Any>
436 installed) when the first message is sent, and follows later
437 C<Log::Any::Adapter-E<gt>set()> calls. If Log::Any or Log::Dispatch dies,
438 C<Carp::carp> is called and the other backends still get the message.
439  
440 A C<Log::Any::Proxy> or C<Log::Dispatch> object given as the C<logger>
441 itself is used in the same way, rather than as an object whose method is
442 called for each level: neither has a method for every level, and both
443 would join the arguments with spaces.
444  
445 A message that reaches a C<Log::Abstraction> while it is being forwarded
446 (e.g. through L<Log::Any::Adapter::Abstraction>) is logged by that logger's
447 other backends but not forwarded again, so a set-up that points back at
448 itself doesn't loop.
449  
450 =head2 File rotation
451  
452 Log files written by path (a scalar C<logger>, a C<file> key in a C<logger>
453 hash, and the top-level C<file>) can be rotated by size, by time, or both:
454  
455 my $log = Log::Abstraction->new(
456 file => '/var/log/myapp.log',
457 rotate_size => '10M',
458 rotate_interval => 'daily',
459 rotate_keep => 7,
460 );
461  
462 Before each write the file is checked, and if it is due it is renamed to
463 F<myapp.log.1>, the old F<.1> to F<.2> and so on, the oldest beyond
464 C<rotate_keep> being deleted; the line then goes to a new F<myapp.log>. A
465 rotation that fails (e.g. for lack of permission) is ignored, and the line is
466 still written. File handles passed as C<fd> aren't rotated.
467  
468 Rotation isn't coordinated between processes: if several processes log to the
469 same file, use B<logrotate> instead.
470  
471 =head3 logrotate
472  
473 The file is kept open between messages, but before each write the logger
474 checks that the path still names the same file (device and inode), so
475 B<logrotate>'s default (rename the file and let the application create a new
476 one) works without C<copytruncate>, and without sending the process a
477 C<SIGHUP>: the next message is written to a new file.
478  
479 A C<postrotate> script that sends the process a C<SIGHUP> works too: except
480 on Windows, the first time a logger opens a file, C<Log::Abstraction> sets
481 C<$SIG{HUP}> to a handler that makes every logger open its files again on
482 the next write. A handler that was already set (a code reference or a sub
483 name) is called after it. This means a C<SIGHUP> no longer ends the
484 program, as it does by default, while a logger that has opened a file
485 exists. When the last of them is destroyed, the handler that was there
486 before is put back. A handler that the program sets later replaces
487 C<Log::Abstraction>'s (and isn't changed when the loggers are destroyed);
488 it can call L</reopen> itself.
489  
490 In case a C<SIGHUP> isn't sent, every file is also closed and opened again
491 every 5 minutes, by default. C<reopen_interval> changes how often, makes
492 C<SIGHUP> the only way (C<-1>), or closes the file after every message
493 (C<0>), as before version 0.40.
494  
495 On Windows an open file can't be renamed or deleted, so a file the logger is
496 writing can only be rotated by the logger itself (which closes it first), or
497 after calling L</reopen>, and then only until the next message.
498  
499 =head1 METHODS
500  
501 =head2 new
502  
503 my $logger = Log::Abstraction->new(%args);
504 my $logger = Log::Abstraction->new(\%args);
505 my $logger = Log::Abstraction->new($file_path);
506  
507 # Clone with optional overrides
508 my $clone = $logger->new(level => 'debug');
509  
510 Creates a new C<Log::Abstraction> instance, or clones an existing one when
511 called on an object. It may also be called as a plain function,
512 C<Log::Abstraction::new(%args)>, which behaves like
513 C<Log::Abstraction-E<gt>new(%args)>.
514  
515 =head3 Arguments
516  
517 =over 4
518  
519 =item * C<carp_on_warn>
520  
521 If set to 1, and no C<logger> is given, call C<Carp::carp> on C<warn()>.
522 Also causes C<error()> to C<carp> if C<croak_on_error> is not set.
523  
524 =item * C<croak_on_error>
525  
526 If set to 1, and no C<logger> is given, call C<Carp::croak> on C<error()>.
527  
528 =item * C<config_file>
529  
530 Path to a configuration file (YAML, XML, INI, etc.) whose contents are
531 merged with the constructor arguments. On non-Windows systems the class
532 can also be configured via environment variables prefixed with
533 C<"Log::Abstraction::">. For example:
534  
535 export Log::Abstraction::script_name=foo
536  
537 =item * C<ctx>
538  
539 Arbitrary context value passed through to CODE-ref logger callbacks as
540 C<$args-E<gt>{ctx}>.
541  
542 =item * C<format>
543  
544 Format string for the file, fd and scalar-path backends; a backend's own
545 C<format> (see L</Per-backend level and format>) overrides it for that
546 backend. Unset or an empty string means the default,
547 C<%level%E<gt> [%timestamp%] %class% %callstack% %message%>. Tokens expanded
548 at log time:
549  
550 %callstack% caller file and line number
551 %class% blessed class of the logger object
552 %level% upper-cased level name
553 %message% the joined log message
554 %timestamp% the time of the call; YYYY-MM-DD HH:MM:SS local time by
555 default (see timestamp_format, timestamp_precision and utc)
556 %env_FOO% value of $ENV{FOO}, or empty string if unset
557  
558 Tokens are only expanded in the format string itself, never in the text
559 of the message. Each line break in a message is followed by a tab, so a
560 continuation line can't be mistaken for a new log entry.
561  
562 The special value C<"json"> (not a format string but a magic keyword) switches
563 all file and fd backends to emit one compact JSON object per log line:
564  
565 {"timestamp":"...","level":"info","message":"...","file":"...","line":42}
566  
567 This format is compatible with log aggregators such as journald, Loki,
568 Elasticsearch, and Splunk. C<class> is included when the logger is a subclass
569 of C<Log::Abstraction>, and C<fields> when the call has L</Structured fields>.
570 Keys are emitted in sorted order.
571  
572 B<Security note:> because a format may contain C<%env_*%> tokens, which
573 expand to environment variables, avoid granting untrusted sources write
574 access to config files that set C<format> or any backend's C<format> (see
575 L</Per-backend level and format>).
576  
577 =item * C<level>
578  
579 Minimum level at which to emit log entries. Defaults to C<"warning">.
580 Valid values (case-insensitive): C<trace>, C<debug>, C<info>/C<informational>,
581 C<notice>, C<warn>/C<warning>, C<error>/C<err>, C<crit>/C<critical>/C<fatal>,
582 C<alert>, C<emerg>/C<emergency>/C<panic>. C<trace> and C<debug> are the same
583 threshold (see L</LIMITATIONS>). It may also be an array reference, whose
584 first element is used, as some configuration-file formats produce.
585  
586 =item * C<max_messages>
587  
588 The most entries to keep in the in-memory history returned by
589 L</messages>; when it is full, the oldest entry is discarded. Must be a
590 non-negative integer; C<0> keeps no history at all. Unlimited by default, which in a long-running process
591 means the history grows without bound.
592  
593 =item * C<logger>
594  
595 One of:
596  
597 =over 4
598  
599 =item * A code reference -- called with a hashref C<{ class, file, line, level, message, ctx, fields }>
600 (C<ctx> and C<fields> only when there are any)
601  
602 =item * An object -- method matching the level name is called on it; a
603 L<Log::Any> logger or a L<Log::Dispatch> object is used as the C<log_any> or
604 C<log_dispatch> backend (see L</Forwarding to Log::Any and Log::Dispatch>)
605  
606 =item * A hash reference -- may contain C<file>, C<array>, C<fd>, C<syslog>, C<journald>, C<sendmail>,
607 C<log_any> and/or C<log_dispatch> keys,
608 each of which may have its own C<level> and C<format> (see L</Per-backend level and format>)
609  
610 =item * An array reference -- C<{ level, message }> hashrefs are pushed onto it, with a
611 C<fields> key when the call has L</Structured fields>
612  
613 =item * A scalar string -- treated as a file path to append to
614  
615 =back
616  
617 When not supplied, L<Log::Log4perl> is initialised as the default backend.
618  
619 The C<sendmail> sub-hash supports:
620 C<host>, C<port>, C<to>, C<from>, C<subject>, C<level>, C<format>,
621 C<min_interval>, C<digest>, C<digest_max>, C<async>. C<to> is required. With C<format>, the email body is the
622 formatted line rather than the message. C<level> may be a level name or a syslog number (0-7);
623 without it, every message is emailed.
624 At most one email is sent per C<min_interval> seconds per instance; the
625 messages in between are dropped, unless C<digest> is set, which sends them
626 with the next email (see L</Email digests>). If delivery fails,
627 C<Carp::carp> is called and the other backends still receive the message.
628  
629 Sending an email waits for the SMTP server, which can take seconds. With
630 C<async =E<gt> 1>, the email is sent by a child process (made with
631 C<fork>), and the log call returns at once. The C<host> and C<port> are
632 still checked first. The logger can't know whether the child succeeded:
633 the child carps a failure itself, and the message (and any digest sent
634 with it) is lost rather than held. Emails sent close together are sent at
635 the same time, so they may arrive in any order. The finished children are
636 reaped the next time an email is sent and when a logger is destroyed; a program that
637 reaps every child itself (e.g. C<waitpid(-1, ...)> in a C<$SIG{CHLD}>
638 handler) may see them. On Windows, whose C<fork> is emulated with threads,
639 when C<fork> fails, and for the email sent when perl exits, the email is
640 sent in the log call as without C<async>.
641  
642 The C<syslog> sub-hash supports the keys below. The message is passed to
643 C<syslog()> through a C<%s> format, so C<%> sequences in it, such as C<%m>,
644 are logged literally.
645  
646 =over 4
647  
648 =item * C<facility> -- the syslog facility (default: C<local0>)
649  
650 =item * C<level> -- only messages at this level or more severe are sent; a level name or a syslog number (0-7)
651  
652 =item * C<format> -- format the message with this (see L</format>) before sending it; by default the message is sent as it is
653  
654 =item * C<host> (or its alias C<server>), and any other L<Sys::Syslog/setlogsock> option -- passed to C<setlogsock()>
655  
656 =back
657  
658 The C<journald> sub-hash sends each message as a single datagram to the
659 systemd journal using the journald native protocol. Supported keys:
660  
661 =over 4
662  
663 =item * C<socket> -- path to the journald socket (default: F</run/systemd/journal/socket>)
664  
665 =item * C<identifier> -- value for the C<SYSLOG_IDENTIFIER> field (default: basename of C<$0>)
666  
667 =item * C<level> -- only messages at this level or more severe are sent; a level name or a syslog number (0-7)
668  
669 =item * C<format> -- the C<MESSAGE> field is the message formatted with this (see L</format>); by default it is the message as it is
670  
671 =item * any other key -- included verbatim as an uppercase journald field name.
672 The upper-cased name must contain only C<A-Z>, C<0-9> and C<_>, and must not
673 start with C<_>; C<new()> croaks otherwise.
674  
675 =back
676  
677 The C<PRIORITY> field is set automatically from the log level (0=emerg...7=debug).
678 A message too large for one datagram (about 200KB) is truncated and
679 C<[truncated]> appended.
680 Delivery failures are silent apart from a single C<Carp::carp> (repeated only
681 after a later send has succeeded); the application is never crashed by a
682 journald error. The socket is opened for the first message and reused for
683 the next ones; after a failed send it is closed, and the next message opens a
684 new one. Each datagram is addressed to the socket path, so delivery
685 continues after journald restarts.
686  
687 =item * C<redact>
688  
689 Patterns to remove from every message before it is logged: a C<qr//>, a
690 string (compiled as a regular expression; a config file can't hold a
691 C<qr//>), or an array reference of them. See L</Redaction>.
692  
693 =item * C<reopen_interval>
694  
695 Log files written by path are kept open between messages. Every this many
696 seconds (default 300, i.e. 5 minutes) each one is closed and opened again on
697 its next write, in case a rotation tool changed the file without renaming it
698 and without sending a C<SIGHUP> (see L</logrotate>).
699  
700 C<0> closes the file after every message, so it is never held open, and no
701 C<SIGHUP> handler is installed for it. C<-1> never reopens the file because
702 of time: only a C<SIGHUP>, L</reopen>, or the file being renamed or deleted
703 does. (Windows has no C<SIGHUP>.)
704  
705 =item * C<rotate_interval>
706  
707 Rotate log files by time: C<hourly>, C<daily>, C<weekly> (weeks start on
708 Monday) or C<monthly>, case-insensitive. Before each write, a file whose
709 last-modified time is in an earlier period than now (in local time, or UTC
710 with C<utc>) is rotated, so a file not written to for a while rotates on the
711 next write. See L</File rotation>.
712  
713 =item * C<rotate_keep>
714  
715 How many rotated files to keep, F<FILE.1> to F<FILE.I<n>> (default 5). With
716 C<0>, a file due for rotation is deleted instead.
717  
718 =item * C<rotate_size>
719  
720 Rotate log files that have reached this size: a number of bytes, optionally
721 followed by C<K>, C<M> or C<G> (powers of 1024), e.g. C<10M>. See
722 L</File rotation>.
723  
724 =item * C<script_name>
725  
726 Script name reported to syslog. Auto-detected from C<$0> if not supplied.
727  
728 =item * C<timestamp_format>
729  
730 How C<%timestamp%>, and the C<timestamp> key of C<format =E<gt> 'json'>,
731 are written. Either a L<POSIX/strftime> pattern (default
732 C<%Y-%m-%d %H:%M:%S>) or one of these names (case-insensitive):
733  
734 iso8601, rfc3339 2026-10-03T20:14:23-04:00, or 2026-10-04T00:14:23Z with utc
735  
736 The pattern may also use:
737  
738 %N fractional seconds, 9 digits (nanoseconds)
739 %3N fractional seconds, 3 digits (milliseconds); any width 1-9
740 %z UTC offset as +hhmm (on every platform, unlike some strftimes)
741 %:z UTC offset as +hh:mm, as RFC 3339 needs
742 %Z the time-zone name; "UTC" when utc is set
743 %% a literal %
744  
745 Fractional seconds come from L<Time::HiRes> and are truncated, not rounded;
746 digits beyond the system clock's resolution (usually microseconds) are
747 noise. The timestamp is taken once per message, so every backend shows the
748 same time.
749  
750 =item * C<timestamp_precision>
751  
752 The number of fractional-second digits, 0-9 (default 0), added after the
753 seconds (each C<%S>) of whichever C<timestamp_format> is in use:
754  
755 Log::Abstraction->new(timestamp_format => 'rfc3339', timestamp_precision => 3, utc => 1);
756 # 2026-10-04T00:14:24.094Z
757  
758 =item * C<utc>
759  
760 If true, timestamps are in UTC rather than local time.
761  
762 =item * C<verbose>
763  
764 When using the default Log::Log4perl backend, raises the logging level to
765 DEBUG when set to a true value.
766  
767 =back
768  
769 =head3 Returns
770  
771 A blessed C<Log::Abstraction> object.
772  
773 =head3 Side Effects
774  
775 Loads C<File::Basename> if C<syslog> is configured (either at the top level
776 or in a C<logger> hash) and C<script_name> is not supplied. Loads
777 C<Log::Log4perl> if no backend (C<logger>, C<file>, C<fd> or C<array>) is
778 specified.
779  
780 Builds one L<Log::Abstraction::Backend> object for each place messages go
781 to. The arguments are not changed: in particular, the C<syslog> hash keeps
782 its C<facility>, C<level> and C<format> keys, and a C<server> key is not
783 renamed C<host> (before 0.40, the first message did both).
784  
785 =head3 Example
786  
787 my $logger = Log::Abstraction->new(
788 level => 'debug',
789 logger => \@messages,
790 );
791  
792 my $clone = $logger->new(level => 'info');
793  
794 =head3 API SPECIFICATION
795  
796 =head4 Input
797  
798 {
799 carp_on_warn => { type => 'boolean', optional => 1 },
800 config_file => { type => 'string', optional => 1 },
801 croak_on_error => { type => 'boolean', optional => 1 },
802 ctx => { optional => 1 },
803 format => { type => 'string', optional => 1 },
804 level => { type => 'string', regex => qr/^(trace|debug|info(?:rmational)?|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|alert|emerg(?:ency)?|panic)$/i, optional => 1 },
805 logger => { optional => 1 },
806 max_messages => { type => 'integer', min => 0, optional => 1 },
807 redact => { optional => 1 }, # regex, string, or arrayref of them
808 reopen_interval => { type => 'integer', min => -1, optional => 1 },
809 rotate_interval => { type => 'string', regex => qr/^(hourly|daily|weekly|monthly)$/i, optional => 1 },
810 rotate_keep => { type => 'integer', min => 0, optional => 1 },
811 rotate_size => { type => 'string', regex => qr/^\s*[1-9]\d*\s*[kmg]?b?\s*$/i, optional => 1 },
812 script_name => { type => 'string', optional => 1 },
813 timestamp_format => { type => 'string', min => 1, optional => 1 },
814 timestamp_precision => { type => 'integer', min => 0, max => 9, optional => 1 },
815 utc => { type => 'boolean', optional => 1 },
816 verbose => { type => 'boolean', optional => 1 },
817 }
818  
819 =head4 Output
820  
821 { type => 'object', class => 'Log::Abstraction' }
822  
823 =head3 MESSAGES
824  
825 Error Meaning / Action
826 ---------------------------------------- -----------------------------------------
827 "<class>: <path>: File not readable" config_file path exists but is unreadable.
828 Check file permissions.
829 "<class>: Can't load configuration Config::Abstraction could not parse the
830 from <path>" file. Check syntax and format.
831 "<class>: syslog needs to know the syslog backend requested but script_name
832 script name" could not be determined. Pass it explicitly.
833 "<class>: attempt to encapsulate logger => Log::Abstraction would create
834 Log::Abstraction as a logging class, a needless forwarding loop. Use a
835 that would add a needless indirection" different backend.
836 "<class>: invalid syslog level '<l>'" level value is not a recognised syslog
837 level name. Use trace/debug/info/notice/
838 warn/warning/error.
839 "<class>: max_messages must be a max_messages is negative or not a number.
840 non-negative integer, not '<v>'"
841 "<class>: rotate_size must be a rotate_size is not, e.g., 1048576, 512K,
842 positive number of bytes, optionally 10M or 1G.
843 with K, M or G, not '<v>'"
844 "<class>: rotate_interval must be rotate_interval is not one of those names.
845 hourly, daily, weekly or monthly,
846 not '<v>'"
847 "<class>: rotate_keep must be a rotate_keep is negative or not a number.
848 non-negative integer, not '<v>'"
849 "<class>: reopen_interval must be a reopen_interval is not a whole number
850 number of seconds, 0 or -1, not '<v>'" of seconds, 0 (close after every
851 message) or -1 (only on SIGHUP).
852 "<class>: timestamp_format must be a timestamp_format is undef, empty or a
853 non-empty string" reference.
854 "<class>: timestamp_precision must be timestamp_precision is not a whole
855 an integer from 0 to 9, not '<v>'" number of digits from 0 to 9.
856 "<class>: redact patterns must be A redact entry is a reference other than
857 regular expressions or non-empty a qr//, or an empty string.
858 strings"
859 "<class>: invalid redact pattern '<p>': A redact string is not a valid regular
860 <error>" expression.
861 "<class>: redact pattern <p> matches the The pattern can match nothing at all
862 empty string" (e.g. qr/x*/), which would put a marker
863 between every character.
864 "<class>: invalid <backend> level '<l>'" A backend's 'level' (file, fd, array,
865 sendmail, journald) is neither a level
866 name nor 0-7. (A bad syslog 'level'
867 gives "invalid syslog level", as above.)
868 "<class>: the <backend> format must be A backend's 'format' is undef, empty or
869 a non-empty string" a reference.
870 "<class>: the <backend> hash needs a The hash form of file, fd, array, log_any
871 '<backend>' key" or log_dispatch has no destination (e.g.
872 file => { level => 'info' } without a
873 'file' key).
874 "<class>: the sendmail backend needs The sendmail sub-hash has no 'to' key.
875 a 'to' address"
876 "<class>: sendmail digest_max must be a digest_max is zero, negative or not a
877 positive integer, not '<v>'" number.
878 "<class>: invalid journald field name An extra journald key, upper-cased, is not
879 '<k>'" [A-Z0-9_] or starts with '_'.
880 "<class>: the logger hash has none of The logger hash has nowhere to send
881 the keys array, fd, file, journald, messages. (Before 0.40, the first
882 log_any, log_dispatch, sendmail, message croaked "Don't know how to deal
883 syslog" with the <level> message".)
884 "<class>: the logger can't be a <TYPE> logger is a reference of an unsupported
885 reference" type, e.g. a SCALAR or GLOB reference.
886 "<class>: log_any must be a Log::Any log_any is neither a Log::Any logger
887 logger or a category name" (Log::Any::Proxy) nor a non-empty string.
888 "<class>: log_any needs Log::Any to be log_any is a category name but Log::Any
889 installed" can't be loaded.
890 "<class>: log_dispatch must be a log_dispatch is not an object with a
891 Log::Dispatch object" log() method.
892  
893 The following are not raised by C<new()> but later, by the logging methods
894 (C<trace>, C<debug>, C<info>, C<notice>, C<warn>, C<error>, C<fatal>,
895 C<critical>, C<alert>, C<emergency>), when
896 a message that passes the level threshold reaches the backend concerned.
897 Croaks are configuration errors; delivery failures only carp, because a
898 logging failure must never crash the application.
899  
900 Croak Meaning / Action
901 ---------------------------------------- -----------------------------------------
902 "<class>: Invalid file name: <path>" A file path (logger string, 'file' key or
903 logger hash 'file') contains one of
904 < > | * ? ; ! ` $ " or a control
905 character, or contains '..'.
906 "<class>: Invalid SMTP host: <host>" The sendmail 'host' contains characters
907 other than A-Z a-z 0-9 . -
908 "<class>: Invalid SMTP port: <port>" The sendmail 'port' is not an integer in
909 1-65535.
910 "<class>: <object class> doesn't know An object logger has no method for this
911 how to deal with the <level> message" level. (notice falls back to info.)
912  
913 Carp Meaning / Action
914 ---------------------------------------- -----------------------------------------
915 "Failed to send email: <error>" SMTP delivery failed. The other backends
916 still receive the message.
917 "<class>: syslog failed: <error>" Sys::Syslog::syslog() died.
918 "<class>: journald send failed: <error>" The journald socket could not be reached.
919 Given once, then not again until a send
920 succeeds.
921 "<class>: Log::Any failed: <error>" Log::Any (or its adapter) died. The other
922 "<class>: Log::Dispatch failed: <error>" backends still receive the message.
923  
924 =head3 PSEUDOCODE
925  
926 FUNCTION new(class_or_obj, args...)
927  
928 Parse args:
929 IF single non-hash scalar
930 THEN store as logger shorthand
931 ELSE extract named params via Params::Get
932  
933 IF config_file present:
934 CROAK if file is not readable
935 Load via Config::Abstraction, merge into args (constructor args win)
936 Restore caller-supplied array ref that config merge would have dropped
937  
938 IF called on a blessed instance (clone form):
939 CROAK on an invalid timestamp_format or timestamp_precision
940 CROAK on an invalid rotate_size, rotate_interval, rotate_keep or
941 reopen_interval, and normalise rotate_size to bytes
942 CROAK on an invalid redact pattern; compile redact to one regex
943 shallow-clone self merged with override args
944 validate and store new level integer if level given in args
945 copy message history list
946 start the clone with no held email digest, no open files, and not
947 counted as a user of the SIGHUP handler
948 count the clone as a user of an open syslog connection
949 build the clone's own backends
950 RETURN clone
951  
952 IF syslog requested (top level or in a logger hash) and script_name
953 not supplied:
954 auto-detect script name via File::Basename
955 CROAK if still undefined
956  
957 IF logger arg is a Log::Abstraction object:
958 CROAK (would create a needless forwarding loop)
959  
960 IF no logger AND no file AND no fd AND no array:
961 load Log::Log4perl, easy_init at DEBUG or ERROR per verbose flag
962 store Log4perl logger as the backend
963  
964 Normalise and validate level:
965 IF level is an arrayref, take first element
966 lc() the level string
967 CROAK if not in syslog_values lookup
968 default to $DEFAULT_LEVEL if not supplied
969  
970 CROAK if max_messages is given and is not a non-negative integer
971 CROAK if timestamp_format is empty or not a string, or
972 timestamp_precision is not an integer 0-9
973 CROAK if rotate_size is not a positive size, rotate_interval is not
974 hourly/daily/weekly/monthly, or rotate_keep or reopen_interval is not
975 a non-negative integer; normalise rotate_size to bytes
976 CROAK if a redact pattern is not a regex or non-empty string, doesn't
977 compile, or matches the empty string; compile redact to one regex
978  
979 FOR each backend (top-level file/fd/array, and the logger hash's
980 file/fd/array/syslog/sendmail/journald/log_any/log_dispatch):
981 IF log_any: CROAK unless a Log::Any::Proxy, or a category name with
982 Log::Any installed
983 IF log_dispatch: CROAK unless an object with a log() method
984 SKIP the rest unless given as a hash
985 CROAK if a file/fd/array/log_any/log_dispatch hash lacks its
986 destination key (its own name)
987 CROAK if its 'level' is not a level name or 0-7
988 CROAK if its 'format' is undef, empty or not a string
989  
990 IF logger is a hash:
991 CROAK if a sendmail sub-hash has no 'to' address, or a digest_max
992 that isn't a positive integer
993 CROAK if an extra journald key is not a valid journald field name
994 CROAK if it has none of the backend keys
995  
996 self = bless { messages => [], merged args, level => numeric } as class
997 self->{_backends} = _build_backends() (CROAK on an unsupported logger)
998 RETURN self
999  
1000 END FUNCTION
1001  
1002 =cut
1003  
1004 1857 ▶sub new {
Subroutine new: called CC=56 SCAR=40.3
Pod documented
1005 1857 my $class = shift;
1006  
1007 # Accept a plain hash, a hashref, or a single scalar (file-path shorthand)
1008 1857 my %args;
1009 1857 ▶ if((scalar(@_) == 1) && (ref($_[0]) ne 'HASH')) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @_ == 1 and ref $_[0] ne 'HASH') { } 7 1850 1857
elsif (my $params = Params::Get::get_params(undef, \@_)) { } 829 1021 1850
Condition100%3/3
scalar @_ == 1 and ref $_[0] ne "HASH"
!ll&&!rl&&r
1837137
MC/DC100%2/2
scalar @_ == 1 and ref $_[0] ne "HASH"
scalar @_ == 1 ref $_[0] ne "HASH"
Truth table100%3/3
A and B
A= scalar @_ == 1B= ref $_[0] ne "HASH"
ABresult
0X0
100
111
1010 7 $args{'logger'} = shift;
1011 } elsif(my $params = Params::Get::get_params(undef, \@_)) {
1012 829 %args = %{$params};
1013 }
1014  
1015 # Load configuration from a file when config_file is present
1016 1857 ▶ if(exists($args{'config_file'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"config_file"}) 11 1846 1857
1017 11 ▶ if(!-r $args{'config_file'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-r $args{"config_file"}) 2 9 11
1018 2 Carp::croak("$class: ", $args{'config_file'}, ': File not readable');
1019 }
1020 9 ▶ if(my $config = Config::Abstraction->new(
Branch: 1 branch
BranchTrueFalseTotal
if (my $config = 'Config::Abstraction'->new('config_dirs', [''], 'config_file', $args{'config_file'}, 'env_prefix', "${class}::")) { } 9 0 9
1021 config_dirs => [''],
1022 config_file => $args{'config_file'},
1023 env_prefix => "${class}::",
1024 )) {
1025 # Merge file config with constructor args; constructor wins
1026 9 $config = $config->all();
1027 9 ▶ if($config->{$class}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{$class}) 2 7 9
1028 2 $config = $config->{$class};
1029 }
1030 9 my $array = $args{'array'};
1031 9 %args = (%{$config}, %args);
1032 # Restore caller-supplied array ref after merge (config can't supply refs)
1033 9 ▶ if($array) {
Branch: 1 branch
BranchTrueFalseTotal
if ($array) 5 4 9
1034 5 $args{'array'} = $array;
1035 }
1036 } else {
1037 0 Carp::croak("$class: Can't load configuration from ", $args{'config_file'});
1038 }
1039 }
1040  
1041 # Handle function-call form: Log::Abstraction::new() with no class
1042 1855 ▶ if(!defined($class)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $class) { } 1 1854 1855
elsif (builtin::blessed($class)) { } 1036 818 1854
1043 1 $class = __PACKAGE__;
1044 } elsif(Scalar::Util::blessed($class)) {
1045 # Called on an existing instance -- return a shallow clone
1046 1036 _check_timestamp_args(ref($class), \%args);
1047 1034 _check_rotate_args(ref($class), \%args);
1048 1032 _check_redact_args(ref($class), \%args);
1049 1031 my $clone = bless { %{$class}, %args }, ref($class);
1050 1031 ▶ if(my $level = $args{'level'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $level = $args{"level"}) 8 1023 1031
1051 8 $level = lc($level);
1052 8 ▶ if(!defined($syslog_values{$level})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Log::Abstraction::syslog_values{$level}) 1 7 8
1053 1 Carp::croak("$class: invalid syslog level '$level'");
1054 }
1055 7 $clone->{level} = $syslog_values{$level};
1056 }
1057 # Copy the message history so parent and clone diverge independently
1058 1030 $clone->{messages} = [ @{$class->{messages}} ];
1059 # A clone has its own digest, or held messages would be sent twice
1060 1030 delete @{$clone}{qw(_email_digest _email_digest_dropped)};
1061 # and opens its own files, so that closing them doesn't affect the parent
1062 1030 delete @{$clone}{qw(_handles _sighup)};
1063 # The clone shares the parent's open syslog connection
1064 1030 ▶ Log::Abstraction::Backend::Syslog->retain_connection() if($clone->{_syslog_opened});
Branch: 1 branch
BranchTrueFalseTotal
if $clone->{"_syslog_opened"} 1 1029 1030
1065 # and has its own backends, as the overrides may change them
1066 1030 $clone->{_backends} = $clone->_build_backends();
1067 1029 return $clone;
1068 }
1069  
1070 # Auto-detect script name when syslog backend is requested, either as a
1071 # top-level key or (the documented form) inside a HASH logger
1072 my $wants_syslog = $args{'syslog'}
1073 819 ▶ || ((ref($args{'logger'}) eq 'HASH') && $args{'logger'}->{'syslog'});
Condition100%6/6
$args{'syslog'} || ref $args{'logger'} eq 'HASH' && $args{'logger'}{'syslog'}
l!l&&r!l&&!r
428787
ref $args{"logger"} eq "HASH" and $args{"logger"}{"syslog"}
!ll&&!rl&&r
64414328
MC/DC100%3/3
$args{'syslog'} || ref $args{'logger'} eq 'HASH' && $args{'logger'}{'syslog'}
$args{'syslog'} ref $args{"logger"} eq "HASH" $args{"logger"}{"syslog"}
Truth table100%4/4
A || B and C
A= $args{'syslog'}B= ref $args{"logger"} eq "HASH"C= $args{"logger"}{"syslog"}
ABCresult
1XX1
0111
00X0
0100
1074 819 ▶ if($wants_syslog && !$args{'script_name'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wants_syslog and not $args{"script_name"}) 6 813 819
Condition100%3/3
$wants_syslog and not $args{"script_name"}
!ll&&!rl&&r
787266
MC/DC100%2/2
$wants_syslog and not $args{"script_name"}
$wants_syslog not $args{"script_name"}
Truth table100%3/3
A and not(B)
A= $wants_syslogB= not $args{"script_name"}
ABresult
0X0
100
111
1075 6 require File::Basename;
1076 6 ▶ $args{'script_name'} = File::Basename::basename($ENV{'SCRIPT_NAME'} || $0);
Condition66%2/3
$ENV{'SCRIPT_NAME'} || $0
l!l&&r!l&&!r
150
MC/DC0%0/2
$ENV{'SCRIPT_NAME'} || $0
$ENV{'SCRIPT_NAME'} $0
Truth table66%2/3
A || B
A= $ENV{'SCRIPT_NAME'}B= $0
ABresult
1X1
011
000
1077 Carp::croak("$class: syslog needs to know the script name")
1078 6 ▶ if(!defined($args{'script_name'}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"script_name"} 0 6 6
1079 }
1080  
1081 # Reject attempts to use this module as its own logger backend
1082 819 ▶ if(defined(my $logger = $args{logger})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined(my $logger = $args{'logger'})) { } 440 379 819
elsif (not $args{'file'} || $args{'fd'} || $args{'array'}) { } 15 364 379
1083 440 ▶ if(Scalar::Util::blessed($logger) && (ref($logger) eq __PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($logger) and ref $logger eq __PACKAGE__) 2 438 440
Condition100%3/3
builtin::blessed($logger) and ref $logger eq __PACKAGE__
!ll&&!rl&&r
419192
MC/DC100%2/2
builtin::blessed($logger) and ref $logger eq __PACKAGE__
builtin::blessed($logger) ref $logger eq __PACKAGE__
Truth table100%3/3
A and B
A= builtin::blessed($logger)B= ref $logger eq __PACKAGE__
ABresult
0X0
100
111
1084 2 Carp::croak(
1085 "$class: attempt to encapsulate ",
1086 __PACKAGE__,
1087 ' as a logging class, that would add a needless indirection',
1088 );
1089 }
1090 ▶ } elsif(!$args{'file'} && !$args{'fd'} && !$args{'array'}) {
Condition100%6/6
$args{'file'} || $args{'fd'} || $args{'array'}
l!l&&r!l&&!r
12623815
$args{"file"} or $args{"fd"}
l!l&&r!l&&!r
7155253
MC/DC100%3/3
$args{'file'} || $args{'fd'} || $args{'array'}
$args{"file"} $args{"fd"} $args{'array'}
Truth table100%4/4
A or B || C
A= $args{"file"}B= $args{"fd"}C= $args{'array'}
ABCresult
1XX1
01X1
0011
0000
1091 # Fall back to Log::Log4perl when no other backend is configured
1092 15 require Log::Log4perl;
1093 15 Log::Log4perl->import();
1094 Log::Log4perl->easy_init(
1095 15 ▶ $args{verbose} ? $Log::Log4perl::DEBUG : $Log::Log4perl::ERROR
Branch: 1 branch
BranchTrueFalseTotal
$args{'verbose'} ? : 1 14 15
1096 );
1097 15 $args{'logger'} = Log::Log4perl->get_logger();
1098 }
1099  
1100 # Resolve and store the numeric threshold for the requested level
1101 817 my $level = $args{'level'};
1102 817 ▶ if($level) {
Branch: 1 branch
BranchTrueFalseTotal
if ($level) { } 688 129 817
1103 688 ▶ if(ref($level) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $level eq "ARRAY") 1 687 688
1104 1 $level = $level->[0];
1105 }
1106 688 $level = lc($level);
1107 688 ▶ if(!defined($syslog_values{$level})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Log::Abstraction::syslog_values{$level}) 3 685 688
1108 3 Carp::croak("$class: invalid syslog level '$level'");
1109 }
1110 685 $args{'level'} = $level;
1111 } else {
1112 129 $args{'level'} = $DEFAULT_LEVEL;
1113 }
1114  
1115 # Cap on the in-memory message history (undef means unlimited)
1116 814 ▶ if(defined(my $max = $args{'max_messages'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $max = $args{"max_messages"})) 4 810 814
1117 4 ▶ if($max !~ /^\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($max =~ /^\d+$/) 1 3 4
1118 1 Carp::croak("$class: max_messages must be a non-negative integer, not '$max'");
1119 }
1120 }
1121  
1122 813 _check_timestamp_args($class, \%args);
1123 805 _check_rotate_args($class, \%args);
1124 788 _check_redact_args($class, \%args);
1125  
1126 # Validate the backends' own 'level' and 'format' keys now, rather than
1127 # have a bad value silently drop messages at log time: the top-level
1128 # file/fd/array and the HASH logger's sub-backends
1129 784 my @backends = map { [ $_, $args{$_} ] } grep { defined($args{$_}) } qw(file fd array);
1130 784 ▶ if(ref($args{'logger'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args{"logger"} eq "HASH") 171 613 784
1131 171 my $hash = $args{'logger'};
1132 204 push @backends, map { [ $_, $hash->{$_} ] }
1133 171 grep { defined($hash->{$_}) } qw(file fd array syslog sendmail journald log_any log_dispatch);
1134 }
1135 784 for my $backend (@backends) {
1136 664 my ($name, $value) = @{$backend};
1137 664 ▶ _check_producer($class, $name, $value) if($name =~ /^log_(?:any|dispatch)$/);
Branch: 1 branch
BranchTrueFalseTotal
if $name =~ /^log_(?:any|dispatch)$/ 15 649 664
1138 659 ▶ next if(ref($value) ne 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
if ref $value ne "HASH" 515 144 659
1139 144 ▶ if(($name =~ /^(?:file|fd|array|log_any|log_dispatch)$/) && !$value->{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^(?:file|fd|array|log_any|log_dispatch)$/ and not $value->{$name}) 7 137 144
Condition100%3/3
$name =~ /^(?:file|fd|array|log_any|log_dispatch)$/ and not $value->{$name}
!ll&&!rl&&r
110277
MC/DC100%2/2
$name =~ /^(?:file|fd|array|log_any|log_dispatch)$/ and not $value->{$name}
$name =~ /^(?:file|fd|array|log_any|log_dispatch)$/ not $value->{$name}
Truth table100%3/3
A and not(B)
A= $name =~ /^(?:file|fd|array|log_any|log_dispatch)$/B= not $value->{$name}
ABresult
0X0
100
111
1140 7 Carp::croak("$class: the $name hash needs a '$name' key");
1141 }
1142 137 my $sub_level = $value->{'level'};
1143 137 ▶ if(defined($sub_level) && !defined(_level_number($sub_level))) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $sub_level and not defined _level_number($sub_level)) 9 128 137
Condition100%3/3
defined $sub_level and not defined _level_number($sub_level)
!ll&&!rl&&r
96329
MC/DC100%2/2
defined $sub_level and not defined _level_number($sub_level)
defined $sub_level not defined _level_number($sub_level)
Truth table100%3/3
A and not(B)
A= defined $sub_levelB= not defined _level_number($sub_level)
ABresult
0X0
100
111
1144 9 Carp::croak("$class: invalid $name level '$sub_level'");
1145 }
1146 128 ▶ if(exists($value->{'format'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $value->{"format"}) 17 111 128
1147 17 my $format = $value->{'format'};
1148 17 ▶ if(!defined($format) || ref($format) || ($format eq '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $format or ref $format or $format eq "") 5 12 17
Condition100%6/6
not defined $format or ref $format or $format eq ""
l!l&&r!l&&!r
2312
not defined $format or ref $format
l!l&&r!l&&!r
1115
MC/DC100%3/3
not defined $format or ref $format or $format eq ""
not defined $format ref $format $format eq ""
Truth table100%4/4
not(A) or B or C
A= not defined $formatB= ref $formatC= $format eq ""
ABCresult
1XX1
01X1
0011
0000
1149 5 Carp::croak("$class: the $name format must be a non-empty string");
1150 }
1151 }
1152 }
1153  
1154 758 ▶ if(ref($args{'logger'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args{"logger"} eq "HASH") 148 610 758
1155 148 my $hash = $args{'logger'};
1156  
1157 148 ▶ if(exists($hash->{'sendmail'})
Branch: 1 branch
BranchTrueFalseTotal
if (exists $hash->{"sendmail"} and ref $hash->{"sendmail"} ne "HASH" || !$hash->{"sendmail"}{"to"}) 1 147 148
Condition83%5/6
exists $hash->{"sendmail"} and ref $hash->{"sendmail"} ne "HASH" || !$hash->{"sendmail"}{"to"}
!ll&&!rl&&r
95521
ref $hash->{"sendmail"} ne "HASH" or not $hash->{"sendmail"}{"to"}
l!l&&r!l&&!r
0152
MC/DC66%2/3
exists $hash->{"sendmail"} and ref $hash->{"sendmail"} ne "HASH" || !$hash->{"sendmail"}{"to"}
exists $hash->{"sendmail"} ref $hash->{"sendmail"} ne "HASH" not $hash->{"sendmail"}{"to"}
Truth table75%3/4
A and B or not(C)
A= exists $hash->{"sendmail"}B= ref $hash->{"sendmail"} ne "HASH"C= not $hash->{"sendmail"}{"to"}
ABCresult
0XX0
1000
11X1
1011
1158 && ((ref($hash->{'sendmail'}) ne 'HASH') || !$hash->{'sendmail'}->{'to'})) {
1159 1 Carp::croak("$class: the sendmail backend needs a 'to' address");
1160 }
1161 147 ▶ if((ref($hash->{'sendmail'}) eq 'HASH') && defined(my $max = $hash->{'sendmail'}->{'digest_max'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $hash->{"sendmail"} eq "HASH" and defined(my $max = $hash->{"sendmail"}{"digest_max"})) 7 140 147
Condition100%3/3
ref $hash->{"sendmail"} eq "HASH" and defined(my $max = $hash->{"sendmail"}{"digest_max"})
!ll&&!rl&&r
95457
MC/DC100%2/2
ref $hash->{"sendmail"} eq "HASH" and defined(my $max = $hash->{"sendmail"}{"digest_max"})
ref $hash->{"sendmail"} eq "HASH" defined(my $max = $hash->{"sendmail"}{"digest_max"})
Truth table100%3/3
A and B
A= ref $hash->{"sendmail"} eq "HASH"B= defined(my $max = $hash->{"sendmail"}{"digest_max"})
ABresult
0X0
100
111
1162 7 ▶ if($max !~ /^[1-9]\d*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($max =~ /^[1-9]\d*$/) 5 2 7
1163 5 Carp::croak("$class: sendmail digest_max must be a positive integer, not '$max'");
1164 }
1165 }
1166  
1167 142 ▶ if(ref($hash->{'journald'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $hash->{"journald"} eq "HASH") 25 117 142
1168 25 for my $key (keys %{$hash->{'journald'}}) {
1169 35 ▶ next if(lc($key) =~ /^(?:socket|identifier|level|format)$/);
Branch: 1 branch
BranchTrueFalseTotal
if lc($key) =~ /^(?:socket|identifier|level|format)$/ 28 7 35
1170 7 ▶ if(uc($key) !~ $RE_JOURNALD_FIELD) {
Branch: 1 branch
BranchTrueFalseTotal
unless (uc($key) =~ /$RE_JOURNALD_FIELD/) 2 5 7
1171 2 Carp::croak("$class: invalid journald field name '$key'");
1172 }
1173 }
1174 }
1175  
1176 # A hash with nowhere to send messages is a mistake
1177 140 ▶ if(!grep { $hash->{$_} } @HASH_BACKENDS) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$hash->{$_};} @HASH_BACKENDS) 3 137 140
1178 3 Carp::croak("$class: the logger hash has none of the keys ", join(', ', sort @HASH_BACKENDS));
1179 }
1180 }
1181  
1182 # Construct the object, and the backends that messages go to
1183 my $self = bless {
1184 messages => [],
1185 %args,
1186 747 level => $syslog_values{ $args{'level'} },
1187 }, $class;
1188 747 $self->{_backends} = $self->_build_backends();
1189 745 return $self;
1190 }
1191  
1192 # ---------------------------------------------------------------------------
1193 # _build_backends -- one Log::Abstraction::Backend object per destination
1194 #
1195 # Purpose: Turn the logger, array, file and fd arguments into the
1196 # objects that _log passes each message to, once, rather than
1197 # working them out again for every message.
1198 # Entry: $self -- the logger object, whose arguments new() has checked.
1199 # Exit: Returns an array reference of backends, in the order they
1200 # get a message: the logger (or the logger hash's file, array,
1201 # sendmail, syslog, journald, log_any, log_dispatch and fd),
1202 # or the top-level array if there is no logger; then the
1203 # top-level file and fd.
1204 # Side effects: None. The caller's hashes are not changed (the syslog
1205 # backend works on a copy).
1206 # Notes: Each backend's own 'level' is converted to a number here.
1207 # Croaks if the logger is a reference of an unsupported type.
1208 #
1209 # Pseudocode:
1210 # FUNCTION _build_backends(self)
1211 # backends = []
1212 # IF logger is set:
1213 # CODE ref -> Code
1214 # ARRAY ref -> Array
1215 # HASH ref -> for each key of HASH_BACKENDS that is set, its
1216 # class, with destination, level and format from
1217 # _backend (syslog, sendmail and journald are hashes
1218 # holding level and format)
1219 # plain string -> File (the path)
1220 # Log::Any::Proxy -> LogAny; Log::Dispatch -> LogDispatch
1221 # other object -> Object
1222 # other ref -> CROAK
1223 # ELSE IF array: Array
1224 # IF top-level file: File; IF top-level fd: Fd
1225 # RETURN backends
1226 # END FUNCTION
1227 # ---------------------------------------------------------------------------
1228 1779 ▶sub _build_backends :Private {
Subroutine _build_backends: called CC=14 SCAR=26.4
1229 1779 my $self = shift;
1230  
1231 1779 my $class = Scalar::Util::blessed($self);
1232 1779 my @backends;
1233  
1234 # Build one backend from a key's value: the destination under the
1235 # backend's own name, plus its level (as a number) and format
1236 1644 ▶ my $build = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1237 1644 my ($name, $value) = @_;
1238 1644 my ($dest, $level, $format);
1239 1644 ▶ if($name =~ /^(?:syslog|sendmail|journald)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name =~ /^(?:syslog|sendmail|journald)$/) { } 98 1546 1644
1240 # These are hashes already, holding their own level and format
1241 98 ▶ $dest = (ref($value) eq 'HASH') ? $value : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' ? : 98 0 98
1242 98 ($level, $format) = @{$dest}{qw(level format)};
1243 } else {
1244 1546 ($dest, $level, $format) = _backend($name, $value);
1245 }
1246 1644 return $BACKEND_CLASS{$name}->new(
1247 $name => $dest,
1248 level => scalar(_level_number($level)),
1249 format => $format,
1250 );
1251 1779 };
1252  
1253 1779 ▶ if(my $logger = $self->{'logger'}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $logger = $self->{'logger'}) { } 400 1379 1779
elsif ($self->{'array'}) { } 1318 61 1379
1254 400 my $type = ref($logger);
1255 400 ▶ if($type eq 'CODE') {
Branch: 7 branches
BranchTrueFalseTotal
if ($type eq 'CODE') { } 34 366 400
elsif ($type eq 'ARRAY') { } 169 197 366
elsif ($type eq 'HASH') { } 141 56 197
elsif (not $type) { } 18 38 56
elsif (builtin::blessed($logger) and $logger->isa('Log::Any::Proxy')) { } 1 37 38
elsif (builtin::blessed($logger) and $logger->isa('Log::Dispatch')) { } 1 36 37
elsif (builtin::blessed($logger)) { } 33 3 36
1256 34 push @backends, Log::Abstraction::Backend::Code->new(code => $logger);
1257 } elsif($type eq 'ARRAY') {
1258 169 push @backends, Log::Abstraction::Backend::Array->new(array => $logger);
1259 } elsif($type eq 'HASH') {
1260 141 push @backends, map { $build->($_, $logger->{$_}) } grep { $logger->{$_} } @HASH_BACKENDS;
1261 } elsif(!$type) {
1262 18 push @backends, Log::Abstraction::Backend::File->new(file => $logger);
1263 ▶ } elsif(Scalar::Util::blessed($logger) && $logger->isa('Log::Any::Proxy')) {
Condition100%3/3
builtin::blessed($logger) and $logger->isa("Log::Any::Proxy")
!ll&&!rl&&r
3341
MC/DC100%2/2
builtin::blessed($logger) and $logger->isa("Log::Any::Proxy")
builtin::blessed($logger) $logger->isa("Log::Any::Proxy")
Truth table100%3/3
A and B
A= builtin::blessed($logger)B= $logger->isa("Log::Any::Proxy")
ABresult
0X0
100
111
1264 # Neither has a method for every level, and both would join
1265 # the arguments with spaces, so they aren't plain objects
1266 1 push @backends, Log::Abstraction::Backend::LogAny->new(log_any => $logger);
1267 ▶ } elsif(Scalar::Util::blessed($logger) && $logger->isa('Log::Dispatch')) {
Condition100%3/3
builtin::blessed($logger) and $logger->isa("Log::Dispatch")
!ll&&!rl&&r
3331
MC/DC100%2/2
builtin::blessed($logger) and $logger->isa("Log::Dispatch")
builtin::blessed($logger) $logger->isa("Log::Dispatch")
Truth table100%3/3
A and B
A= builtin::blessed($logger)B= $logger->isa("Log::Dispatch")
ABresult
0X0
100
111
1268 1 push @backends, Log::Abstraction::Backend::LogDispatch->new(log_dispatch => $logger);
1269 } elsif(Scalar::Util::blessed($logger)) {
1270 33 push @backends, Log::Abstraction::Backend::Object->new(object => $logger);
1271 } else {
1272 3 Carp::croak("$class: the logger can't be a $type reference");
1273 }
1274 } elsif($self->{'array'}) {
1275 # A top-level array is only used when there's no logger
1276 1318 push @backends, $build->('array', $self->{'array'});
1277 }
1278  
1279 # Top-level file and fd keys (parallel to 'logger')
1280 1776 for my $name (qw(file fd)) {
1281 3552 ▶ push @backends, $build->($name, $self->{$name}) if($self->{$name});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{$name} 153 3399 3552
1282 }
1283  
1284 1776 return \@backends;
1285 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1286  
1287 # ---------------------------------------------------------------------------
1288 # _sanitize_email_header -- remove CR/LF to prevent SMTP header injection
1289 #
1290 # Purpose: Strip carriage-return and line-feed characters from any string
1291 # that will appear in a MIME header field (To, From, Subject).
1292 # Entry: $value -- a scalar, possibly containing \r, \n, or \r\n.
1293 # Exit: Returns the sanitised scalar, or undef if input was undef.
1294 # Notes: Called from _log before every header_set() call.
1295 # ---------------------------------------------------------------------------
1296 117 ▶sub _sanitize_email_header :Private {
Subroutine _sanitize_email_header: called CC=2 SCAR=6.9
1297 117 my ($value) = @_;
1298  
1299 117 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1 116 117
1300  
1301 # Strip all CR, LF and CRLF sequences
1302 116 $value =~ s/\r\n?|\n//g;
1303  
1304 116 return Return::Set::set_return(
1305 $value,
1306 { type => 'string', 'matches' => qr/^[^\r\n]*$/ },
1307 );
1308 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1309  
1310 # ---------------------------------------------------------------------------
1311 # _level_number -- convert a level name or number to its numeric threshold
1312 #
1313 # Purpose: Let sub-backend 'level' keys (syslog, sendmail) be given
1314 # either as a name ('warning', case-insensitive) or as a syslog
1315 # number (0-7), and compare them consistently.
1316 # Entry: $value -- a level name or an integer.
1317 # Exit: Returns the integer threshold, or undef if $value is neither
1318 # a recognised level name nor an integer in 0-7.
1319 # Notes: A pure function (no $self), called as _level_number($value).
1320 # ---------------------------------------------------------------------------
1321 1707 ▶sub _level_number :Private {
Subroutine _level_number: called CC=4 SCAR=13.9
1322 1707 my ($value) = @_;
1323  
1324 1707 ▶ return unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 1613 94 1707
1325  
1326 94 ▶ if($value =~ /^\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /^\d+$/) 18 76 94
1327 18 ▶ return ($value <= $DEBUG) ? $value + 0 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$value <= $Log::Abstraction::DEBUG ? : 15 3 18
1328 }
1329 76 return $syslog_values{lc($value)};
1330 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1331  
1332 # ---------------------------------------------------------------------------
1333 # _backend -- split a file, fd or array backend's value into its parts
1334 #
1335 # Purpose: These backends take either their destination (a path, a
1336 # handle, an array ref) or a hash holding the destination under
1337 # the backend's own name plus optional 'level' and 'format'.
1338 # Entry: $name -- 'file', 'fd' or 'array'.
1339 # $value -- the configured value.
1340 # Exit: Returns (destination, level, format); level and format are
1341 # undef for the plain form.
1342 # Notes: A pure function (no $self), called as _backend($name, $value).
1343 # Only an unblessed hash is the hash form, so a handle object
1344 # is still a destination.
1345 # ---------------------------------------------------------------------------
1346 1565 ▶sub _backend :Private {
Subroutine _backend: called CC=2 SCAR=6.9
1347 1565 my ($name, $value) = @_;
1348  
1349 1565 ▶ return ($value, undef, undef) unless(ref($value) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 1538 27 1565
1350 27 return ($value->{$name}, $value->{'level'}, $value->{'format'});
1351 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1352  
1353 # ---------------------------------------------------------------------------
1354 # _check_producer -- validate a log_any or log_dispatch backend in new()
1355 #
1356 # Purpose: Catch a wrong destination when the logger is built rather
1357 # than at the first message.
1358 # Entry: $class -- the class name, for messages.
1359 # $name -- 'log_any' or 'log_dispatch'.
1360 # $value -- the configured value, plain or hash form.
1361 # Exit: Returns nothing; croaks on an invalid destination.
1362 # Notes: A pure function (no $self). log_any takes a Log::Any::Proxy
1363 # or a category name, which needs Log::Any installed;
1364 # log_dispatch takes a Log::Dispatch (or anything with a
1365 # Log::Dispatch-style log() method).
1366 # ---------------------------------------------------------------------------
1367 15 ▶sub _check_producer :Private {
Subroutine _check_producer: called CC=10 SCAR=23.1
1368 15 my ($class, $name, $value) = @_;
1369  
1370 15 my ($dest) = _backend($name, $value);
1371 15 ▶ return if(!defined($dest)); # a hash form without one croaks later
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dest 1 14 15
1372  
1373 14 ▶ if($name eq 'log_any') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "log_any") 5 9 14
1374 5 ▶ if(Scalar::Util::blessed($dest)) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($dest)) { } 2 3 5
elsif (not ref $dest and length $dest) { } 2 2 4
1375 2 ▶ return if($dest->isa('Log::Any::Proxy'));
Branch: 1 branch
BranchTrueFalseTotal
if $dest->isa("Log::Any::Proxy") 1 1 2
1376 ▶ } elsif(!ref($dest) && length($dest)) {
Condition66%2/3
not ref $dest and length $dest
!ll&&!rl&&r
102
MC/DC50%1/2
not ref $dest and length $dest
not ref $dest length $dest
Truth table66%2/3
not(A) and B
A= not ref $destB= length $dest
ABresult
0X0
100
111
1377 2 ▶ return if(eval { require Log::Any; 1 });
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require Log::Any; 1 } } 2 0 2
1378 0 Carp::croak("$class: log_any needs Log::Any to be installed");
1379 }
1380 2 Carp::croak("$class: log_any must be a Log::Any logger or a category name");
1381 }
1382 9 ▶ if(!Scalar::Util::blessed($dest) || !$dest->can('log')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not builtin::blessed($dest) && $dest->can("log")) 3 6 9
Condition100%3/3
builtin::blessed($dest) && $dest->can('log')
!ll&&!rl&&r
126
MC/DC100%2/2
builtin::blessed($dest) && $dest->can('log')
builtin::blessed($dest) $dest->can('log')
Truth table100%3/3
A && B
A= builtin::blessed($dest)B= $dest->can('log')
ABresult
0X0
100
111
1383 3 Carp::croak("$class: log_dispatch must be a Log::Dispatch object");
1384 }
1385 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1386  
1387 # ---------------------------------------------------------------------------
1388 # _to_json -- encode a data structure as a compact, canonical JSON string
1389 #
1390 # Purpose: One place to build and use the cached JSON::PP encoder, for
1391 # format => 'json' lines and for reference-valued fields.
1392 # Entry: $data -- a reference to encode.
1393 # Exit: Returns a character string (not UTF-8 bytes). Falls back to
1394 # Perl's stringification if the data can't be encoded (e.g. it
1395 # is nested too deeply), so logging never dies.
1396 # Notes: A pure function (no $self), called as _to_json($data).
1397 # Blessed objects and other values JSON can't represent are
1398 # encoded as null.
1399 # ---------------------------------------------------------------------------
1400 62 ▶sub _to_json :Private {
Subroutine _to_json: called CC=3 SCAR=11.0
1401 62 my ($data) = @_;
1402  
1403 62 require JSON::PP;
1404 62 ▶ $json_encoder ||= JSON::PP->new->canonical(1)->allow_blessed(1)->allow_unknown(1);
Condition66%2/3
$json_encoder ||= "JSON::PP"->new->canonical(1)->allow_blessed(1)->allow_unknown(1)
l!l&&r!l&&!r
5570
MC/DC0%0/2
$json_encoder ||= "JSON::PP"->new->canonical(1)->allow_blessed(1)->allow_unknown(1)
$json_encoder "JSON::PP"->new->canonical(1)->allow_blessed(1)->allow_unknown(1)
Truth table66%2/3
A ||= B
A= $json_encoderB= "JSON::PP"->new->canonical(1)->allow_blessed(1)->allow_unknown(1)
ABresult
1X1
011
000
1405 62 my $json = eval { $json_encoder->encode($data) };
1406 62 ▶ return $json // "$data";
Condition100%2/2
$json // "$data"
l!l
611
MC/DC100%1/1
$json // "$data"
$json
Truth table100%2/2
A
A= $json
Aresult
11
00
1407 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1408  
1409 # ---------------------------------------------------------------------------
1410 # _field_string -- turn one structured-field value into a plain string
1411 #
1412 # Purpose: Text backends and journald need a string for each field.
1413 # Entry: $value -- the field value: a scalar, an object, or a reference.
1414 # Exit: Returns '' for undef, the stringified object for a blessed
1415 # value (so overloaded stringification is honoured), JSON for
1416 # any other reference, and the value itself otherwise.
1417 # Notes: A pure function (no $self), called as _field_string($value).
1418 # ---------------------------------------------------------------------------
1419 126 ▶sub _field_string :Private {
Subroutine _field_string: called CC=4 SCAR=13.9
1420 126 my ($value) = @_;
1421  
1422 126 ▶ return '' unless defined($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 4 122 126
1423 122 ▶ return "$value" if(!ref($value) || Scalar::Util::blessed($value));
Branch: 1 branch
BranchTrueFalseTotal
if not ref $value or builtin::blessed($value) 92 30 122
Condition100%3/3
not ref $value or builtin::blessed($value)
l!l&&r!l&&!r
88430
MC/DC100%2/2
not ref $value or builtin::blessed($value)
not ref $value builtin::blessed($value)
Truth table100%3/3
not(A) or B
A= not ref $valueB= builtin::blessed($value)
ABresult
1X1
011
000
1424 30 return _to_json($value);
1425 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1426  
1427 # ---------------------------------------------------------------------------
1428 # _fields_text -- render structured fields as logfmt-style key=value pairs
1429 #
1430 # Purpose: Text formats, syslog, email and object backends have no field
1431 # support, so the fields are appended to the message as text.
1432 # Entry: $fields -- a hashref of field names to values.
1433 # Exit: Returns 'key=value key2="value 2"', with keys in sorted order.
1434 # Notes: A pure function (no $self), called as _fields_text($fields).
1435 # Characters outside [\w.-] in a key become '_'. A value that
1436 # is empty or contains white space, '"', '=' or '\' is quoted,
1437 # with '"' and '\' escaped and control characters written as
1438 # \n, \r, \t or \xNN, so a field can never contain a line break
1439 # and forge a log entry.
1440 # ---------------------------------------------------------------------------
1441 71 ▶sub _fields_text :Private {
Subroutine _fields_text: called CC=5 SCAR=16.1
1442 71 my ($fields) = @_;
1443  
1444 71 my %escapes = ("\n" => '\n', "\r" => '\r', "\t" => '\t');
1445 71 my @pairs;
1446 71 for my $name (sort keys %{$fields}) {
1447 105 (my $key = $name) =~ s/[^\w.\-]/_/g;
1448 105 my $value = _field_string($fields->{$name});
1449 105 ▶ if(($value eq '') || ($value =~ /[\s"=\\\x00-\x1F\x7F]/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value eq "" or $value =~ /[\s"=\\\x00-\x1F\x7F]/) 30 75 105
Condition100%3/3
$value eq "" or $value =~ /[\s"=\\\x00-\x1F\x7F]/
l!l&&r!l&&!r
62475
MC/DC100%2/2
$value eq "" or $value =~ /[\s"=\\\x00-\x1F\x7F]/
$value eq "" $value =~ /[\s"=\\\x00-\x1F\x7F]/
Truth table100%3/3
A or B
A= $value eq ""B= $value =~ /[\s"=\\\x00-\x1F\x7F]/
ABresult
1X1
011
000
1450 30 $value =~ s/(["\\])/\\$1/g;
1451 30 ▶ $value =~ s/([\x00-\x1F\x7F])/$escapes{$1} \/\/ sprintf('\\x%02x', ord($1))/ge;
Condition100%2/2
$escapes{$1} // sprintf("\\x%02x", ord $1)
l!l
51
MC/DC100%1/1
$escapes{$1} // sprintf("\\x%02x", ord $1)
$escapes{$1}
Truth table100%2/2
A
A= $escapes{$1}
Aresult
11
00
1452 30 $value = qq{"$value"};
1453 }
1454 105 push @pairs, "$key=$value";
1455 }
1456 71 return join(' ', @pairs);
1457 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1458  
1459 # ---------------------------------------------------------------------------
1460 # _check_timestamp_args -- validate the timestamp options given to new()
1461 #
1462 # Purpose: Croak in new() (and when cloning) on a bad timestamp_format
1463 # or timestamp_precision, rather than log a broken timestamp.
1464 # Entry: $class -- the class name, for the error message.
1465 # $args -- hashref of constructor arguments.
1466 # Exit: Returns nothing; croaks on an invalid value.
1467 # Notes: A pure function (no $self), called as
1468 # _check_timestamp_args($class, \%args).
1469 # ---------------------------------------------------------------------------
1470 1858 ▶sub _check_timestamp_args :Private {
Subroutine _check_timestamp_args: called CC=8 SCAR=20.8
1471 1858 my ($class, $args) = @_;
1472  
1473 1858 ▶ if(exists($args->{'timestamp_format'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{"timestamp_format"}) 44 1814 1858
1474 44 my $format = $args->{'timestamp_format'};
1475 44 ▶ if(!defined($format) || ref($format) || ($format eq '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $format or ref $format or $format eq "") 6 38 44
Condition100%6/6
not defined $format or ref $format or $format eq ""
l!l&&r!l&&!r
4238
not defined $format or ref $format
l!l&&r!l&&!r
2240
MC/DC100%3/3
not defined $format or ref $format or $format eq ""
not defined $format ref $format $format eq ""
Truth table100%4/4
not(A) or B or C
A= not defined $formatB= ref $formatC= $format eq ""
ABCresult
1XX1
01X1
0011
0000
1476 6 Carp::croak("$class: timestamp_format must be a non-empty string");
1477 }
1478 }
1479 1852 ▶ if(defined(my $precision = $args->{'timestamp_precision'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $precision = $args->{"timestamp_precision"})) 37 1815 1852
1480 37 ▶ if(($precision !~ /^\d+$/) || ($precision > $MAX_TIMESTAMP_PRECISION)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $precision =~ /^\d+$/ or $precision > $MAX_TIMESTAMP_PRECISION) 11 26 37
Condition100%3/3
not $precision =~ /^\d+$/ or $precision > $MAX_TIMESTAMP_PRECISION
l!l&&r!l&&!r
8326
MC/DC100%2/2
not $precision =~ /^\d+$/ or $precision > $MAX_TIMESTAMP_PRECISION
not $precision =~ /^\d+$/ $precision > $MAX_TIMESTAMP_PRECISION
Truth table100%3/3
not(A) or B
A= not $precision =~ /^\d+$/B= $precision > $MAX_TIMESTAMP_PRECISION
ABresult
1X1
011
000
1481 11 Carp::croak("$class: timestamp_precision must be an integer from 0 to $MAX_TIMESTAMP_PRECISION, not '$precision'");
1482 }
1483 }
1484 1841 return;
1485 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1486  
1487 # ---------------------------------------------------------------------------
1488 # _utc_offset -- the local time zone's offset from UTC at a given time
1489 #
1490 # Purpose: Portable %z/%:z, and local period boundaries for rotation.
1491 # Entry: $secs -- epoch seconds.
1492 # $utc -- true to return 0 (timestamps are in UTC).
1493 # Exit: Returns the offset in seconds (negative west of Greenwich).
1494 # Notes: A pure function (no $self), called as _utc_offset($secs, $utc).
1495 # The offset is what the local broken-down time would be as
1496 # UTC, less the real time. The year is passed in full so that
1497 # Time::Local doesn't guess a century.
1498 # ---------------------------------------------------------------------------
1499 32 ▶sub _utc_offset :Private {
Subroutine _utc_offset: called CC=2 SCAR=6.9
1500 32 my ($secs, $utc) = @_;
1501  
1502 32 ▶ return 0 if($utc);
Branch: 1 branch
BranchTrueFalseTotal
if $utc 9 23 32
1503 23 my @tm = localtime($secs);
1504 23 return Time::Local::timegm(@tm[0..4], $tm[5] + 1900) - $secs;
1505 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1506  
1507 # ---------------------------------------------------------------------------
1508 # _check_rotate_args -- validate and normalise the file-rotation options
1509 #
1510 # Purpose: Croak in new() (and when cloning) on a bad rotate_size,
1511 # rotate_interval or rotate_keep, rather than fail at log time.
1512 # Entry: $class -- the class name, for the error message.
1513 # $args -- hashref of constructor arguments; changed in place.
1514 # Exit: Returns nothing. rotate_size becomes a number of bytes and
1515 # rotate_interval is lower-cased. Croaks on an invalid value.
1516 # Notes: A pure function (no $self), called as
1517 # _check_rotate_args($class, \%args).
1518 # ---------------------------------------------------------------------------
1519 1854 ▶sub _check_rotate_args :Private {
Subroutine _check_rotate_args: called CC=10 SCAR=23.0
1520 1854 my ($class, $args) = @_;
1521  
1522 1854 ▶ if(defined(my $size = $args->{'rotate_size'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $size = $args->{"rotate_size"})) 53 1801 1854
1523 53 ▶ if($size !~ /^\s*(\d+)\s*([kmg]?)b?\s*$/i || ($1 == 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $size =~ /^\s*(\d+)\s*([kmg]?)b?\s*$/i or $1 == 0) 12 41 53
Condition100%3/3
not $size =~ /^\s*(\d+)\s*([kmg]?)b?\s*$/i or $1 == 0
l!l&&r!l&&!r
9341
MC/DC100%2/2
not $size =~ /^\s*(\d+)\s*([kmg]?)b?\s*$/i or $1 == 0
not $size =~ /^\s*(\d+)\s*([kmg]?)b?\s*$/i $1 == 0
Truth table100%3/3
not(A) or B
A= not $size =~ /^\s*(\d+)\s*([kmg]?)b?\s*$/iB= $1 == 0
ABresult
1X1
011
000
1524 12 Carp::croak("$class: rotate_size must be a positive number of bytes, optionally with K, M or G, not '$size'");
1525 }
1526 41 $args->{'rotate_size'} = $1 * $SIZE_UNITS{lc($2)};
1527 }
1528 1842 ▶ if(defined(my $interval = $args->{'rotate_interval'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $interval = $args->{"rotate_interval"})) 17 1825 1842
1529 17 ▶ if(!$ROTATE_PERIOD{lc($interval)}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ROTATE_PERIOD{lc $interval}) 5 12 17
1530 5 Carp::croak("$class: rotate_interval must be hourly, daily, weekly or monthly, not '$interval'");
1531 }
1532 12 $args->{'rotate_interval'} = lc($interval);
1533 }
1534 1837 ▶ if(defined(my $keep = $args->{'rotate_keep'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $keep = $args->{"rotate_keep"})) 26 1811 1837
1535 26 ▶ if($keep !~ /^\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($keep =~ /^\d+$/) 4 22 26
1536 4 Carp::croak("$class: rotate_keep must be a non-negative integer, not '$keep'");
1537 }
1538 }
1539 1833 ▶ if(defined(my $interval = $args->{'reopen_interval'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $interval = $args->{"reopen_interval"})) 11 1822 1833
1540 11 ▶ if($interval !~ /^(?:\d+|-1)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($interval =~ /^(?:\d+|-1)\z/) 6 5 11
1541 6 Carp::croak("$class: reopen_interval must be a number of seconds, 0 or -1, not '$interval'");
1542 }
1543 }
1544 1827 return;
1545 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1546  
1547 # ---------------------------------------------------------------------------
1548 # _check_redact_args -- validate the redact option and compile it
1549 #
1550 # Purpose: Croak in new() (and when cloning) on a bad redact pattern,
1551 # rather than leave a secret in the log.
1552 # Entry: $class -- the class name, for the error message.
1553 # $args -- hashref of constructor arguments; changed in place.
1554 # Exit: Returns nothing. redact, a regex, a string or an arrayref of
1555 # them, becomes one regex that matches any of them, or undef
1556 # when there are none. Croaks on a pattern that isn't a regex
1557 # or non-empty string, doesn't compile, or matches ''.
1558 # Notes: A pure function (no $self), called as
1559 # _check_redact_args($class, \%args). Strings are allowed
1560 # because a config file can't hold a qr//. One combined regex
1561 # means one pass, so a replacement is never matched again.
1562 #
1563 # Pseudocode:
1564 # FUNCTION _check_redact_args(class, args)
1565 # RETURN unless args has a redact key
1566 # patterns = the defined elements of redact (an arrayref) or redact itself
1567 # FOR each pattern that isn't already a regex:
1568 # CROAK if it is a reference or ''
1569 # compile it (in eval); CROAK with the error, less its location, if
1570 # it doesn't compile
1571 # IF no patterns: set redact to undef; RETURN
1572 # CROAK if any pattern matches ''
1573 # set redact to qr/(?:p1)|(?:p2)|.../
1574 # END FUNCTION
1575 # ---------------------------------------------------------------------------
1576 1820 ▶sub _check_redact_args :Private {
Subroutine _check_redact_args: called CC=11 SCAR=24.0
1577 1820 my ($class, $args) = @_;
1578  
1579 1820 ▶ return if(!exists($args->{'redact'}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args->{"redact"} 1788 32 1820
1580 32 my $redact = $args->{'redact'};
1581 32 ▶ my @patterns = grep { defined } ((ref($redact) eq 'ARRAY') ? @{$redact} : ($redact));
Branch: 1 branch
BranchTrueFalseTotal
ref $redact eq 'ARRAY' ? : 11 21 32
1582 32 for my $pattern (@patterns) {
1583 33 ▶ next if(re::is_regexp($pattern));
Branch: 1 branch
BranchTrueFalseTotal
if &re::is_regexp($pattern) 23 10 33
1584 10 ▶ if(ref($pattern) || ($pattern eq '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pattern or $pattern eq "") 2 8 10
Condition100%3/3
ref $pattern or $pattern eq ""
l!l&&r!l&&!r
118
MC/DC100%2/2
ref $pattern or $pattern eq ""
ref $pattern $pattern eq ""
Truth table100%3/3
A or B
A= ref $patternB= $pattern eq ""
ABresult
1X1
011
000
1585 2 Carp::croak("$class: redact patterns must be regular expressions or non-empty strings");
1586 }
1587 8 my $re = eval { qr/$pattern/ };
1588 8 ▶ if(!$re) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($re) 2 6 8
1589 2 (my $error = $@) =~ s/ at \S+ line \d+\.?\n\z//;
1590 2 Carp::croak("$class: invalid redact pattern '$pattern': $error");
1591 }
1592 6 $pattern = $re;
1593 }
1594 28 ▶ if(!@patterns) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@patterns) 4 24 28
1595 4 $args->{'redact'} = undef;
1596 4 return;
1597 }
1598 24 for my $pattern (@patterns) {
1599 # It would put a marker between every character
1600 28 ▶ if('' =~ $pattern) {
Branch: 1 branch
BranchTrueFalseTotal
if ("" =~ /$pattern/) 1 27 28
1601 1 Carp::croak("$class: redact pattern $pattern matches the empty string");
1602 }
1603 }
1604 23 my $any = join('|', map { "(?:$_)" } @patterns);
1605 23 $args->{'redact'} = qr/$any/;
1606 23 return;
1607 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1608  
1609 # ---------------------------------------------------------------------------
1610 # _redact -- replace whatever matches the redact regex with [REDACTED]
1611 #
1612 # Purpose: Remove secrets from a message or a structured-field value
1613 # before it reaches the history or any backend.
1614 # Entry: $re -- the regex built by _check_redact_args.
1615 # $value -- a string, or a field value of any kind.
1616 # $seen -- (recursion only) the references being walked.
1617 # Exit: Returns the redacted copy; the value itself is unchanged.
1618 # Plain hashes and arrays are copied with their contents
1619 # redacted; a blessed object whose stringification matches
1620 # becomes the redacted string; any other value is returned
1621 # as it is. A reference that contains itself is replaced by
1622 # the marker where it recurs.
1623 # Notes: A pure function (no $self), called as _redact($re, $value).
1624 #
1625 # Pseudocode:
1626 # FUNCTION _redact(re, value, seen)
1627 # RETURN value if undef
1628 # IF blessed: RETURN _redact(re, "value") if "value" matches re, else value
1629 # IF a reference:
1630 # RETURN value unless a plain HASH or ARRAY
1631 # RETURN the marker if value is in seen (it contains itself)
1632 # add value to seen while walking it (local, so siblings may share it)
1633 # RETURN a copy with each element/value passed through _redact
1634 # replace every match of re in (a copy of) value with the marker
1635 # RETURN it
1636 # END FUNCTION
1637 # ---------------------------------------------------------------------------
1638 60 ▶sub _redact :Private {
Subroutine _redact: called CC=10 SCAR=23.0
1639 60 my ($re, $value, $seen) = @_;
1640  
1641 60 ▶ return $value if(!defined($value));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 60 60
1642 60 ▶ if(Scalar::Util::blessed($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($value)) 4 56 60
1643 4 my $string = "$value";
1644 4 ▶ return $value unless $string =~ $re;
Branch: 1 branch
BranchTrueFalseTotal
unless $string =~ /$re/ 2 2 4
1645 2 $string =~ s/$re/$REDACTED_MARKER/g;
1646 2 return $string;
1647 }
1648 56 ▶ if(my $type = ref($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = ref $value) 17 39 56
1649 17 ▶ return $value if(($type ne 'HASH') && ($type ne 'ARRAY'));
Branch: 1 branch
BranchTrueFalseTotal
if $type ne "HASH" and $type ne "ARRAY" 1 16 17
Condition100%3/3
$type ne "HASH" and $type ne "ARRAY"
!ll&&!rl&&r
1331
MC/DC100%2/2
$type ne "HASH" and $type ne "ARRAY"
$type ne "HASH" $type ne "ARRAY"
Truth table100%3/3
A and B
A= $type ne "HASH"B= $type ne "ARRAY"
ABresult
0X0
100
111
1650 16 ▶ $seen ||= {};
Condition100%2/2
$seen ||= {}
l!l
79
MC/DC100%1/1
$seen ||= {}
$seen
Truth table100%2/2
A
A= $seen
Aresult
11
00
1651 16 ▶ return $REDACTED_MARKER if($seen->{$value});
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$value} 1 15 16
1652 15 local $seen->{$value} = 1;
1653 return ($type eq 'HASH')
1654 18 ? { map { $_ => _redact($re, $value->{$_}, $seen) } keys %{$value} }
1655 15 ▶ : [ map { _redact($re, $_, $seen) } @{$value} ];
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'HASH' ? : 12 3 15
1656 }
1657 39 $value =~ s/$re/$REDACTED_MARKER/g;
1658 39 return $value;
1659 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1660  
1661 # ---------------------------------------------------------------------------
1662 # _rotate -- rotate a log file if it is too big or from an earlier period
1663 #
1664 # Purpose: Size- and time-based rotation for the file backends.
1665 # Entry: $self -- the logger object (rotate_size, rotate_interval,
1666 # rotate_keep and utc).
1667 # $path -- the validated log-file path, about to be appended to.
1668 # Exit: Returns nothing. Croaks if a rename fails (autodie);
1669 # _write_line calls this in an eval of its own, so the line is
1670 # still written.
1671 # Side effects: Renames FILE to FILE.1, FILE.1 to FILE.2 and so on, deleting
1672 # FILE.<rotate_keep>; with rotate_keep 0, deletes FILE.
1673 # Notes: Called before each write, so it costs one stat() per line.
1674 # Time-based rotation compares the file's last-modified time
1675 # with now, so a file not written to for a while rotates on the
1676 # next write. Not safe for several processes rotating the same
1677 # file; use logrotate for that.
1678 #
1679 # Pseudocode:
1680 # FUNCTION _rotate(self, path)
1681 # RETURN unless stat(path) succeeds (no file yet)
1682 # due = rotate_size AND file size >= rotate_size
1683 # IF NOT due AND rotate_interval:
1684 # period = ROTATE_PERIOD{rotate_interval}
1685 # due = period(mtime) < period(now), each with its own UTC offset
1686 # RETURN unless due
1687 # close the logger's handle on path
1688 # keep = rotate_keep // 5
1689 # IF keep == 0: unlink path; RETURN
1690 # unlink path.keep if it exists
1691 # FOR i = keep-1 down to 1: rename path.i to path.(i+1) if it exists
1692 # rename path to path.1
1693 # END FUNCTION
1694 # ---------------------------------------------------------------------------
1695 49 ▶sub _rotate :Private {
Subroutine _rotate: called CC=11 SCAR=24.0
1696 49 my ($self, $path) = @_;
1697  
1698 49 ▶ my @st = stat($path) or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@st) = stat $path or return 39 10 49
1699 39 my ($size, $mtime) = @st[7, 9];
1700  
1701 39 ▶ my $due = $self->{'rotate_size'} && ($size >= $self->{'rotate_size'});
Condition100%3/3
$self->{'rotate_size'} && $size >= $self->{'rotate_size'}
!ll&&!rl&&r
11622
MC/DC100%2/2
$self->{'rotate_size'} && $size >= $self->{'rotate_size'}
$self->{'rotate_size'} $size >= $self->{'rotate_size'}
Truth table100%3/3
A && B
A= $self->{'rotate_size'}B= $size >= $self->{'rotate_size'}
ABresult
0X0
100
111
1702 39 ▶ if(!$due && (my $interval = $self->{'rotate_interval'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $due and my $interval = $self->{"rotate_interval"}) 12 27 39
Condition100%3/3
not $due and my $interval = $self->{"rotate_interval"}
!ll&&!rl&&r
22512
MC/DC100%2/2
not $due and my $interval = $self->{"rotate_interval"}
not $due my $interval = $self->{"rotate_interval"}
Truth table100%3/3
not(A) and B
A= not $dueB= my $interval = $self->{"rotate_interval"}
ABresult
0X0
100
111
1703 12 my $utc = $self->{'utc'};
1704 12 my $period = $ROTATE_PERIOD{$interval};
1705 12 my $now = time();
1706 12 $due = $period->($mtime, _utc_offset($mtime, $utc), $utc) < $period->($now, _utc_offset($now, $utc), $utc);
1707 }
1708 39 ▶ return unless($due);
Branch: 1 branch
BranchTrueFalseTotal
unless $due 11 28 39
1709  
1710 # Close the file first: Windows can't rename or delete an open file
1711 28 $self->_close_files($path);
1712  
1713 28 ▶ my $keep = $self->{'rotate_keep'} // $DEFAULT_ROTATE_KEEP;
Condition66%2/3
$self->{"rotate_keep"} // $DEFAULT_ROTATE_KEEP
l!l&&r!l&&!r
11170
MC/DC0%0/2
$self->{"rotate_keep"} // $DEFAULT_ROTATE_KEEP
$self->{"rotate_keep"} $DEFAULT_ROTATE_KEEP
Truth table66%2/3
A // B
A= $self->{"rotate_keep"}B= $DEFAULT_ROTATE_KEEP
ABresult
1X1
011
000
1714 28 ▶ if($keep == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keep == 0) 2 26 28
1715 2 unlink($path);
1716 2 return;
1717 }
1718 # Unlink before each rename: Windows can't rename onto an existing file
1719 26 ▶ unlink("$path.$keep") if(-e "$path.$keep");
Branch: 1 branch
BranchTrueFalseTotal
if -e "$path.$keep" 6 20 26
1720 25 for my $i (reverse(1 .. $keep - 1)) {
1721 74 ▶ rename("$path.$i", "$path." . ($i + 1)) if(-e "$path.$i");
Branch: 1 branch
BranchTrueFalseTotal
if -e "$path.$i" 22 52 74
1722 }
1723 25 rename($path, "$path.1");
1724 25 return;
1725 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1726  
1727 # ---------------------------------------------------------------------------
1728 # _timestamp -- the time of a log call, formatted for log lines
1729 #
1730 # Purpose: Single source of %timestamp% and the JSON 'timestamp' value,
1731 # honouring timestamp_format, utc and timestamp_precision.
1732 # Entry: $self -- the logger object.
1733 # $now -- optional epoch seconds, possibly fractional
1734 # (default: Time::HiRes::time()).
1735 # Exit: Returns the formatted timestamp string.
1736 # Notes: Extends strftime with %N (fractional seconds; %3N, %6N etc.
1737 # give that many digits, truncated, not rounded), %z (+hhmm)
1738 # and %:z (+hh:mm), computed here because Windows' strftime
1739 # gives a zone name for %z; and in UTC, %Z is 'UTC'. A '%%'
1740 # is passed through, so '%%N' is a literal '%N'.
1741 #
1742 # Pseudocode:
1743 # FUNCTION _timestamp(self, now)
1744 # now = now // Time::HiRes::time(); secs = int(now)
1745 # tm = utc ? gmtime(secs) : localtime(secs)
1746 # format = timestamp_format, or the default
1747 # 'iso8601'/'rfc3339' (any case) -> '%Y-%m-%dT%H:%M:%S' + ('Z' if utc, else '%:z')
1748 # IF timestamp_precision > 0: follow each %S with '.%<precision>N'
1749 # Replace, in one pass:
1750 # %% -> %% (left for strftime)
1751 # %nN -> first n (default 9) digits of the fraction of now
1752 # %z -> +hhmm, %:z -> +hh:mm (offset = timegm(tm) - secs; 0 in UTC)
1753 # %Z -> 'UTC' if utc (else left for strftime)
1754 # RETURN strftime(format, tm)
1755 # END FUNCTION
1756 # ---------------------------------------------------------------------------
1757 11140 ▶sub _timestamp :Private {
Subroutine _timestamp: called CC=14 SCAR=26.5
1758 11140 my ($self, $now) = @_;
1759  
1760 11140 ▶ $now //= Time::HiRes::time();
Condition66%2/3
$now //= &Time::HiRes::time()
l!l&&r!l&&!r
10111300
MC/DC0%0/2
$now //= &Time::HiRes::time()
$now &Time::HiRes::time()
Truth table66%2/3
A //= B
A= $nowB= &Time::HiRes::time()
ABresult
1X1
011
000
1761 11140 my $secs = int($now);
1762 11140 my $utc = $self->{'utc'};
1763 11140 ▶ my @tm = $utc ? gmtime($secs) : localtime($secs);
Branch: 1 branch
BranchTrueFalseTotal
$utc ? : 33 11107 11140
1764  
1765 11140 ▶ my $format = $self->{'timestamp_format'} // $DEFAULT_TIMESTAMP_FORMAT;
Condition66%2/3
$self->{"timestamp_format"} // $DEFAULT_TIMESTAMP_FORMAT
l!l&&r!l&&!r
31111090
MC/DC0%0/2
$self->{"timestamp_format"} // $DEFAULT_TIMESTAMP_FORMAT
$self->{"timestamp_format"} $DEFAULT_TIMESTAMP_FORMAT
Truth table66%2/3
A // B
A= $self->{"timestamp_format"}B= $DEFAULT_TIMESTAMP_FORMAT
ABresult
1X1
011
000
1766 11140 ▶ if($format =~ /^(?:iso8601|rfc3339)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($format =~ /^(?:iso8601|rfc3339)$/i) 15 11125 11140
1767 15 ▶ $format = $RFC3339_TIMESTAMP_FORMAT . ($utc ? 'Z' : '%:z');
Branch: 1 branch
BranchTrueFalseTotal
$utc ? : 12 3 15
1768 }
1769 11140 ▶ if(my $precision = $self->{'timestamp_precision'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $precision = $self->{"timestamp_precision"}) 12 11128 11140
1770 12 ▶ $format =~ s/%(%|S)/($1 eq 'S') ? "%S.%${precision}N" : '%%'/ge;
Branch: 1 branch
BranchTrueFalseTotal
$1 eq 'S' ? : 12 4 16
1771 }
1772  
1773 10 ▶ my $offset = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1774 10 my ($colon) = @_;
1775 10 my $diff = _utc_offset($secs, $utc);
1776 10 ▶ my $sign = ($diff < 0) ? '-' : '+';
Branch: 1 branch
BranchTrueFalseTotal
$diff < 0 ? : 5 5 10
1777 10 $diff = abs($diff);
1778 10 return sprintf('%s%02d%s%02d', $sign, int($diff / 3600), $colon, int(($diff % 3600) / 60));
1779 11140 };
1780  
1781 11140 $format =~ s/%(%|([1-9]?)N|:z|z|Z)/
1782 40 ▶ ($1 eq '%') ? '%%'
Branch: 5 branches
BranchTrueFalseTotal
$1 eq '%' ? : 6 34 40
defined $2 ? : 21 13 34
$1 eq ':z' ? : 6 7 13
$1 eq 'z' ? : 4 3 7
$utc ? : 3 0 3
Condition66%2/3
$2 || $MAX_TIMESTAMP_PRECISION
l!l&&r!l&&!r
1920
MC/DC0%0/2
$2 || $MAX_TIMESTAMP_PRECISION
$2 $MAX_TIMESTAMP_PRECISION
Truth table66%2/3
A || B
A= $2B= $MAX_TIMESTAMP_PRECISION
ABresult
1X1
011
000
1783 : defined($2) ? substr(sprintf('%09d', int(($now - $secs) * 1e9)), 0, $2 || $MAX_TIMESTAMP_PRECISION)
1784 : ($1 eq ':z') ? $offset->(':')
1785 : ($1 eq 'z') ? $offset->('')
1786 : $utc ? 'UTC' : '%Z'/gex;
1787  
1788 11140 return POSIX::strftime($format, @tm);
1789 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1790  
1791 # ---------------------------------------------------------------------------
1792 # _write_line -- append one formatted line to a file path or filehandle
1793 #
1794 # Purpose: Single output path for the file, fd and scalar-path backends.
1795 # Entry: $self -- the logger object.
1796 # $target -- a validated file path, or an open filehandle.
1797 # $line -- the formatted line, without trailing newline.
1798 # Exit: Returns nothing.
1799 # Side effects: Appends to the file or prints to the handle. A file path
1800 # is rotated first if rotate_size or rotate_interval says so,
1801 # and is kept open for the next line (see _file_handle), unless
1802 # reopen_interval is 0.
1803 # Notes: Character strings are encoded to UTF-8, avoiding "Wide
1804 # character" warnings, unless the handle already has a
1805 # :utf8 or :encoding layer. File I/O failures are silent by
1806 # design: an I/O error must never crash the application.
1807 # ---------------------------------------------------------------------------
1808 225 ▶sub _write_line :Private {
Subroutine _write_line: called CC=11 SCAR=24.0
1809 225 my ($self, $target, $line) = @_;
1810  
1811 225 ▶ if(ref($target)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $target) 65 160 225
1812 65 ▶ if(utf8::is_utf8($line)
Branch: 1 branch
BranchTrueFalseTotal
if (utf8::is_utf8($line) and not grep({/^(?:utf8|encoding)/;} &PerlIO::get_layers($target))) 2 63 65
Condition100%3/3
utf8::is_utf8($line) and not grep({/^(?:utf8|encoding)/;} &PerlIO::get_layers($target))
!ll&&!rl&&r
6122
MC/DC100%2/2
utf8::is_utf8($line) and not grep({/^(?:utf8|encoding)/;} &PerlIO::get_layers($target))
utf8::is_utf8($line) not grep({/^(?:utf8|encoding)/;} &PerlIO::get_layers($target))
Truth table100%3/3
A and not(B)
A= utf8::is_utf8($line)B= not grep({/^(?:utf8|encoding)/;} &PerlIO::get_layers($target))
ABresult
0X0
100
111
1813 8 && !grep { /^(?:utf8|encoding)/ } PerlIO::get_layers($target)) {
1814 2 utf8::encode($line);
1815 }
1816 65 print $target "$line\n";
1817 65 return;
1818 }
1819  
1820 160 ▶ utf8::encode($line) if(utf8::is_utf8($line));
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($line) 3 157 160
1821  
1822 # Rotate in its own eval: if a rename fails (autodie), still write the line
1823 160 ▶ if($self->{'rotate_size'} || $self->{'rotate_interval'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"rotate_size"} or $self->{"rotate_interval"}) 43 117 160
Condition100%3/3
$self->{"rotate_size"} or $self->{"rotate_interval"}
l!l&&r!l&&!r
349117
MC/DC100%2/2
$self->{"rotate_size"} or $self->{"rotate_interval"}
$self->{"rotate_size"} $self->{"rotate_interval"}
Truth table100%3/3
A or B
A= $self->{"rotate_size"}B= $self->{"rotate_interval"}
ABresult
1X1
011
000
1824 43 eval { $self->_rotate($target) };
1825 }
1826 # A failed write closes the file, so that the next one opens it again
1827 160 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $fout = $self->_file_handle($target); print $fout "$line\n" or die "${target}: $!"; 1 } } or $self->_close_files($target) 156 4 160
1828 160 my $fout = $self->_file_handle($target);
1829 157 ▶ print $fout "$line\n" or die "$target: $!";
Branch: 1 branch
BranchTrueFalseTotal
print $fout "$line\n" or die "${target}: $!" 156 1 157
1830 156 1;
1831 } or $self->_close_files($target);
1832  
1833 # reopen_interval 0: never hold the file open, as before 0.40
1834 160 ▶ if(($self->{'reopen_interval'} // $DEFAULT_REOPEN_INTERVAL) == $REOPEN_EVERY_WRITE) {
Branch: 1 branch
BranchTrueFalseTotal
if (($self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL) == $REOPEN_EVERY_WRITE) 2 158 160
Condition66%2/3
$self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL
l!l&&r!l&&!r
111490
MC/DC0%0/2
$self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL
$self->{"reopen_interval"} $DEFAULT_REOPEN_INTERVAL
Truth table66%2/3
A // B
A= $self->{"reopen_interval"}B= $DEFAULT_REOPEN_INTERVAL
ABresult
1X1
011
000
1835 2 $self->_close_files($target);
1836 }
1837 160 return;
1838 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1839  
1840 # ---------------------------------------------------------------------------
1841 # _file_handle -- the logger's open handle on a log file
1842 #
1843 # Purpose: Keep log files open between messages, rather than opening
1844 # and closing them for every line.
1845 # Entry: $self -- the logger object (reopen_interval, and the open
1846 # handles in $self->{_handles}).
1847 # $path -- a validated log-file path.
1848 # Exit: Returns a handle open for appending, with autoflush on.
1849 # Croaks (autodie) if the file can't be opened.
1850 # Side effects: Opens the file if the logger hasn't, or opens it again if
1851 # the path is now a different file (renamed or deleted, e.g.
1852 # by logrotate), the process has had a SIGHUP, or
1853 # reopen_interval seconds have passed since it was opened
1854 # (never with -1). Installs the SIGHUP handler
1855 # (_catch_sighup) when it opens a file, unless reopen_interval
1856 # is 0, when _write_line closes the file again at once.
1857 # Notes: Costs one stat() per line. The device and inode are taken
1858 # from the path, not the handle, so that the two are compared
1859 # alike (Windows' fstat can differ).
1860 #
1861 # Pseudocode:
1862 # FUNCTION _file_handle(self, path)
1863 # IF the logger has a handle on path:
1864 # RETURN it IF path still names the same device and inode AND
1865 # there has been no SIGHUP since it was opened AND
1866 # (reopen_interval is -1 OR it was opened less than that long ago)
1867 # close it
1868 # install the SIGHUP handler, unless done already, on Windows, or
1869 # reopen_interval is 0
1870 # open path for appending, autoflush on
1871 # remember the handle, path's device and inode, the SIGHUP count and
1872 # the time
1873 # RETURN the handle
1874 # END FUNCTION
1875 # ---------------------------------------------------------------------------
1876 160 ▶sub _file_handle :Private {
Subroutine _file_handle: called CC=11 SCAR=24.1
1877 160 my ($self, $path) = @_;
1878  
1879 160 ▶ if(my $open = $self->{_handles}{$path}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $open = $self->{"_handles"}{$path}) 42 118 160
1880 42 my @st = stat($path);
1881 42 ▶ my $interval = $self->{'reopen_interval'} // $DEFAULT_REOPEN_INTERVAL;
Condition66%2/3
$self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL
l!l&&r!l&&!r
5370
MC/DC0%0/2
$self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL
$self->{"reopen_interval"} $DEFAULT_REOPEN_INTERVAL
Truth table66%2/3
A // B
A= $self->{"reopen_interval"}B= $DEFAULT_REOPEN_INTERVAL
ABresult
1X1
011
000
1882 42 ▶ if(@st && ($st[0] == $open->{dev}) && ($st[1] == $open->{ino})
Branch: 1 branch
BranchTrueFalseTotal
if (@st and $st[0] == $open->{"dev"} and $st[1] == $open->{"ino"} and $open->{"sighup"} == $sighup_count and $interval == $REOPEN_ON_SIGHUP || time - $open->{"opened"} < $interval) 35 7 42
Condition86%13/15
@st and $st[0] == $open->{"dev"} and $st[1] == $open->{"ino"} and $open->{"sighup"} == $sighup_count and $interval == $REOPEN_ON_SIGHUP || time - $open->{"opened"} < $interval
!ll&&!rl&&r
5235
@st and $st[0] == $open->{"dev"} and $st[1] == $open->{"ino"} and $open->{"sighup"} == $sighup_count
!ll&&!rl&&r
3237
@st and $st[0] == $open->{"dev"} and $st[1] == $open->{"ino"}
!ll&&!rl&&r
3039
@st and $st[0] == $open->{"dev"}
!ll&&!rl&&r
3039
$interval == $REOPEN_ON_SIGHUP or time - $open->{"opened"} < $interval
l!l&&r!l&&!r
1342
MC/DC66%4/6
@st and $st[0] == $open->{"dev"} and $st[1] == $open->{"ino"} and $open->{"sighup"} == $sighup_count and $interval == $REOPEN_ON_SIGHUP || time - $open->{"opened"} < $interval
@st $st[0] == $open->{"dev"} $st[1] == $open->{"ino"} $open->{"sighup"} == $sighup_count $interval == $REOPEN_ON_SIGHUP time - $open->{"opened"} < $interval
Truth table71%5/7
A and B and C and D and E or F
A= @stB= $st[0] == $open->{"dev"}C= $st[1] == $open->{"ino"}D= $open->{"sighup"} == $sighup_countE= $interval == $REOPEN_ON_SIGHUPF= time - $open->{"opened"} < $interval
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
1111000
11111X1
1111011
1883 && ($open->{sighup} == $sighup_count)
1884 && (($interval == $REOPEN_ON_SIGHUP) || ((time() - $open->{opened}) < $interval))) {
1885 35 return $open->{fh};
1886 }
1887 7 $self->_close_files($path);
1888 }
1889  
1890 125 ▶ $self->_catch_sighup() unless(($self->{'reopen_interval'} // $DEFAULT_REOPEN_INTERVAL) == $REOPEN_EVERY_WRITE);
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL) == $REOPEN_EVERY_WRITE 123 2 125
Condition66%2/3
$self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL
l!l&&r!l&&!r
101150
MC/DC0%0/2
$self->{"reopen_interval"} // $DEFAULT_REOPEN_INTERVAL
$self->{"reopen_interval"} $DEFAULT_REOPEN_INTERVAL
Truth table66%2/3
A // B
A= $self->{"reopen_interval"}B= $DEFAULT_REOPEN_INTERVAL
ABresult
1X1
011
000
1891 125 open(my $fh, '>>', $path);
1892 122 $fh->autoflush(1);
1893 122 my @st = stat($path);
1894 122 $self->{_handles}{$path} = {
1895 fh => $fh, dev => $st[0], ino => $st[1], sighup => $sighup_count, opened => time(),
1896 };
1897 122 return $fh;
1898 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1899  
1900 # ---------------------------------------------------------------------------
1901 # _catch_sighup -- reopen the log files when the process gets a SIGHUP
1902 #
1903 # Purpose: logrotate's postrotate script, and similar tools, send
1904 # SIGHUP to tell a program to reopen its log files.
1905 # Entry: $self -- the logger opening a file.
1906 # Exit: Returns nothing.
1907 # Side effects: Except on Windows, counts the logger as a user of the
1908 # handler (_sighup), and if no logger has installed it, saves
1909 # $SIG{HUP} and sets it to a handler that counts the signal
1910 # (see $sighup_count) and then calls the saved handler, if it
1911 # is a code reference or a sub name. So SIGHUP doesn't end
1912 # the process by default while a logger uses the handler;
1913 # _release_sighup puts the saved one back.
1914 # Notes: Called when a file is opened, so a program that never logs
1915 # to a file keeps its SIGHUP behaviour. A handler the program
1916 # sets afterwards replaces this one; reopen_interval still
1917 # reopens the files.
1918 # ---------------------------------------------------------------------------
1919 123 ▶sub _catch_sighup :Private {
Subroutine _catch_sighup: called CC=11 SCAR=25.0
1920 123 my $self = $_[0];
1921  
1922 123 ▶ return if($self->{_sighup} || ($^O eq 'MSWin32'));
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_sighup"} or $^O eq "MSWin32" 28 95 123
Condition66%2/3
$self->{"_sighup"} or $^O eq "MSWin32"
l!l&&r!l&&!r
28095
MC/DC50%1/2
$self->{"_sighup"} or $^O eq "MSWin32"
$self->{"_sighup"} $^O eq "MSWin32"
Truth table66%2/3
A or B
A= $self->{"_sighup"}B= $^O eq "MSWin32"
ABresult
1X1
011
000
1923 95 $self->{_sighup} = 1;
1924 95 $sighup_users++;
1925 95 ▶ return if($sighup_handler);
Branch: 1 branch
BranchTrueFalseTotal
if $sighup_handler 6 89 95
1926  
1927 89 $sighup_previous = $SIG{HUP};
1928 89 my $chain = $sighup_previous;
1929 89 ▶ if(defined($chain) && !ref($chain)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $chain and not ref $chain) 63 26 89
Condition100%3/3
defined $chain and not ref $chain
!ll&&!rl&&r
141263
MC/DC100%2/2
defined $chain and not ref $chain
defined $chain not ref $chain
Truth table100%3/3
A and not(B)
A= defined $chainB= not ref $chain
ABresult
0X0
100
111
1930 63 ▶ $chain = undef if(($chain eq '') || ($chain eq 'IGNORE') || ($chain eq 'DEFAULT'));
Branch: 1 branch
BranchTrueFalseTotal
if $chain eq "" or $chain eq "IGNORE" or $chain eq "DEFAULT" 63 0 63
Condition33%2/6
$chain eq "" or $chain eq "IGNORE" or $chain eq "DEFAULT"
l!l&&r!l&&!r
0630
$chain eq "" or $chain eq "IGNORE"
l!l&&r!l&&!r
0063
MC/DC0%0/3
$chain eq "" or $chain eq "IGNORE" or $chain eq "DEFAULT"
$chain eq "" $chain eq "IGNORE" $chain eq "DEFAULT"
Truth table25%1/4
A or B or C
A= $chain eq ""B= $chain eq "IGNORE"C= $chain eq "DEFAULT"
ABCresult
1XX1
01X1
0011
0000
1931 63 ▶ $chain = "main::$chain" if(defined($chain) && ($chain !~ /::/));
Branch: 1 branch
BranchTrueFalseTotal
if defined $chain and not $chain =~ /::/ 0 63 63
Condition33%1/3
defined $chain and not $chain =~ /::/
!ll&&!rl&&r
6300
MC/DC0%0/2
defined $chain and not $chain =~ /::/
defined $chain not $chain =~ /::/
Truth table33%1/3
A and not(B)
A= defined $chainB= not $chain =~ /::/
ABresult
0X0
100
111
1932 }
1933 1 ▶ $sighup_handler = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1934 1 $sighup_count++;
1935 1 ▶ if(defined($chain)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $chain) 1 0 1
1936 42 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1937 1 $chain->(@_);
1938 }
1939 89 };
1940 89 $SIG{HUP} = $sighup_handler;
1941 89 return;
1942 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1943  
1944 # ---------------------------------------------------------------------------
1945 # _release_sighup -- stop using the SIGHUP handler
1946 #
1947 # Purpose: Give the program its own SIGHUP handler back when no logger
1948 # needs this module's.
1949 # Entry: $self -- a logger being destroyed.
1950 # Exit: Returns nothing.
1951 # Side effects: If the logger used the handler and was the last to, puts
1952 # back the $SIG{HUP} that _catch_sighup replaced, unless the
1953 # program has set a handler of its own since; the next logger
1954 # to open a file installs the handler again.
1955 # ---------------------------------------------------------------------------
1956 94 ▶sub _release_sighup :Private {
Subroutine _release_sighup: called CC=8 SCAR=22.4
1957 94 my $self = $_[0];
1958  
1959 94 ▶ return unless(delete $self->{_sighup});
Branch: 1 branch
BranchTrueFalseTotal
unless delete $self->{"_sighup"} 0 94 94
1960 94 ▶ return if(--$sighup_users > 0);
Branch: 1 branch
BranchTrueFalseTotal
if --$sighup_users > 0 6 88 94
1961  
1962 88 my $current = $SIG{HUP};
1963 88 ▶ if($sighup_handler && ref($current) && ($current == $sighup_handler)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sighup_handler and ref $current and $current == $sighup_handler) 88 0 88
Condition33%2/6
$sighup_handler and ref $current and $current == $sighup_handler
!ll&&!rl&&r
0088
$sighup_handler and ref $current
!ll&&!rl&&r
0088
MC/DC0%0/3
$sighup_handler and ref $current and $current == $sighup_handler
$sighup_handler ref $current $current == $sighup_handler
Truth table25%1/4
A and B and C
A= $sighup_handlerB= ref $currentC= $current == $sighup_handler
ABCresult
0XX0
10X0
1100
1111
1964 88 ▶ $SIG{HUP} = (defined($sighup_previous) && length($sighup_previous)) ? $sighup_previous : 'DEFAULT';
Branch: 1 branch
BranchTrueFalseTotal
defined $sighup_previous && length $sighup_previous ? : 74 14 88
Condition66%2/3
defined $sighup_previous and length $sighup_previous
!ll&&!rl&&r
14074
MC/DC50%1/2
defined $sighup_previous and length $sighup_previous
defined $sighup_previous length $sighup_previous
Truth table66%2/3
A and B
A= defined $sighup_previousB= length $sighup_previous
ABresult
0X0
100
111
1965 }
1966 88 $sighup_handler = $sighup_previous = undef;
1967 88 return;
1968 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1969  
1970 # ---------------------------------------------------------------------------
1971 # _close_files -- close log files that the logger holds open
1972 #
1973 # Purpose: Used by reopen(), before a rotation, and after a failed write.
1974 # Entry: $self -- the logger object.
1975 # @paths -- the files to close; none means all of them.
1976 # Exit: Returns nothing.
1977 # Side effects: Closes the handles and forgets them, so the next write opens
1978 # the file again. A failing close is ignored.
1979 # ---------------------------------------------------------------------------
1980 46 ▶sub _close_files :Private {
Subroutine _close_files: called CC=5 SCAR=16.1
1981 46 my ($self, @paths) = @_;
1982  
1983 46 ▶ my $handles = $self->{_handles} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $handles = $self->{"_handles"} or return 35 11 46
1984 35 ▶ for my $path (@paths ? @paths : keys(%{$handles})) {
Branch: 1 branch
BranchTrueFalseTotal
@paths ? : 31 4 35
1985 35 ▶ my $open = delete $handles->{$path} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $open = delete $handles->{$path} or next 32 3 35
1986 32 eval { close($open->{fh}) };
1987 }
1988 35 return;
1989 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1990  
1991 # ---------------------------------------------------------------------------
1992 # _send_email -- send one email: any held digest, then the new lines
1993 #
1994 # Purpose: The sendmail backend's delivery, shared by _log and flush().
1995 # Entry: $self -- the logger object (the digest and throttle state).
1996 # $sm -- the sendmail hash (to, from, subject, host, port,
1997 # digest, async).
1998 # @lines -- the bodies of the new messages (none from flush).
1999 # Exit: Returns 1 if the email was sent or there was nothing to
2000 # send, 0 if delivery failed.
2001 # Side effects: Croaks on an invalid host or port, before the eval so that
2002 # the misconfiguration isn't hidden. On success, clears the
2003 # digest and starts the min_interval throttle. On failure,
2004 # carps, and with digest holds @lines for the next email (the
2005 # digest already held stays held).
2006 # Notes: The body is the held lines, a "... and N more" line if some
2007 # were dropped, then @lines, one per line; a single message
2008 # with nothing held is sent exactly as it is.
2009 # With async (not on Windows, nor while perl is exiting), a
2010 # forked child sends the email and this returns 1 at once, as
2011 # if it had been sent: the child carps a failure itself, and
2012 # the lines are lost. If fork fails, the email is sent here.
2013 #
2014 # Pseudocode:
2015 # FUNCTION _send_email(self, sm, lines...)
2016 # CROAK if host contains unsafe characters, or port isn't 1-65535
2017 # body = held digest, "... and N more" if N were dropped, lines
2018 # RETURN 1 if body is empty
2019 # deliver = load Email::* modules; build email with sanitised headers
2020 # and body joined with newlines; send via SMTP transport
2021 # IF sm->{async} AND not Windows AND perl isn't exiting:
2022 # reap finished children
2023 # fork
2024 # IN THE CHILD: (eval) deliver; CARP on failure; _exit
2025 # IN THE PARENT, if the fork worked: remember the child; clear the
2026 # digest; record the time for the throttle; RETURN 1
2027 # (eval) deliver
2028 # IF it failed:
2029 # CARP; IF sm->{digest}: hold each of lines; RETURN 0
2030 # clear the digest; record the time for the throttle; RETURN 1
2031 # END FUNCTION
2032 # ---------------------------------------------------------------------------
2033 66 ▶sub _send_email :Private {
Subroutine _send_email: called CC=22 SCAR=33.4
2034 66 my ($self, $sm, @lines) = @_;
2035  
2036 # Validate host and port before any eval so bad config croaks immediately
2037 66 ▶ my $host = $sm->{'host'} || $DEFAULT_SMTP_HOST;
Condition66%2/3
$sm->{'host'} || $DEFAULT_SMTP_HOST
l!l&&r!l&&!r
25410
MC/DC0%0/2
$sm->{'host'} || $DEFAULT_SMTP_HOST
$sm->{'host'} $DEFAULT_SMTP_HOST
Truth table66%2/3
A || B
A= $sm->{'host'}B= $DEFAULT_SMTP_HOST
ABresult
1X1
011
000
2038 66 ▶ Carp::croak(ref($self), ": Invalid SMTP host: $host")
Branch: 1 branch
BranchTrueFalseTotal
if $host =~ /$RE_SAFE_HOST/ 4 62 66
2039 if $host =~ $RE_SAFE_HOST;
2040 62 ▶ my $port = $sm->{'port'} || $DEFAULT_SMTP_PORT;
Condition66%2/3
$sm->{'port'} || $DEFAULT_SMTP_PORT
l!l&&r!l&&!r
7550
MC/DC0%0/2
$sm->{'port'} || $DEFAULT_SMTP_PORT
$sm->{'port'} $DEFAULT_SMTP_PORT
Truth table66%2/3
A || B
A= $sm->{'port'}B= $DEFAULT_SMTP_PORT
ABresult
1X1
011
000
2041 62 ▶ Carp::croak(ref($self), ": Invalid SMTP port: $port")
Branch: 1 branch
BranchTrueFalseTotal
unless $port =~ /$RE_PORT/ and $port >= $MIN_PORT and $port <= $MAX_PORT 4 58 62
Condition50%3/6
$port =~ /$RE_PORT/ and $port >= $MIN_PORT and $port <= $MAX_PORT
!ll&&!rl&&r
0458
$port =~ /$RE_PORT/ and $port >= $MIN_PORT
!ll&&!rl&&r
0062
MC/DC33%1/3
$port =~ /$RE_PORT/ and $port >= $MIN_PORT and $port <= $MAX_PORT
$port =~ /$RE_PORT/ $port >= $MIN_PORT $port <= $MAX_PORT
Truth table50%2/4
A and B and C
A= $port =~ /$RE_PORT/B= $port >= $MIN_PORTC= $port <= $MAX_PORT
ABCresult
0XX0
10X0
1100
1111
2042 unless $port =~ $RE_PORT
2043 && $port >= $MIN_PORT
2044 && $port <= $MAX_PORT;
2045  
2046 58 my $dropped = $self->{_email_digest_dropped};
2047 my @body = (
2048 58 ▶ @{$self->{_email_digest} || []},
Branch: 2 branches
BranchTrueFalseTotal
$dropped ? : 3 55 58
$dropped == 1 ? : 1 2 3
Condition100%2/2
$self->{'_email_digest'} || []
l!l
1642
MC/DC100%1/1
$self->{'_email_digest'} || []
$self->{'_email_digest'}
Truth table100%2/2
A
A= $self->{'_email_digest'}
Aresult
11
00
2049 ($dropped ? ("... and $dropped more " . (($dropped == 1) ? 'message' : 'messages')) : ()),
2050 @lines,
2051 );
2052 58 ▶ return 1 if(!@body);
Branch: 1 branch
BranchTrueFalseTotal
unless @body 0 58 58
2053  
2054 # Load mail modules lazily; called in an eval to handle delivery failures
2055 51 ▶ my $deliver = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2056 51 require Email::Simple;
2057 51 require Email::Sender::Simple;
2058 51 require Email::Sender::Transport::SMTP;
2059  
2060 # Build the email object with sanitised headers
2061 51 my $email = Email::Simple->new('');
2062 51 $email->header_set('to', _sanitize_email_header($sm->{'to'}));
2063 51 ▶ $email->header_set('from', _sanitize_email_header($sm->{'from'} || $DEFAULT_FROM_ADDR));
Condition66%2/3
$sm->{'from'} || $DEFAULT_FROM_ADDR
l!l&&r!l&&!r
3480
MC/DC0%0/2
$sm->{'from'} || $DEFAULT_FROM_ADDR
$sm->{'from'} $DEFAULT_FROM_ADDR
Truth table66%2/3
A || B
A= $sm->{'from'}B= $DEFAULT_FROM_ADDR
ABresult
1X1
011
000
2064 51 ▶ if(my $subject = $sm->{'subject'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $subject = $sm->{"subject"}) 2 49 51
2065 2 $email->header_set('subject', _sanitize_email_header($subject));
2066 }
2067 51 $email->body_set(join("\n", @body));
2068  
2069 51 my $transport = Email::Sender::Transport::SMTP->new({
2070 host => $host,
2071 port => $port,
2072 });
2073 # A class method, rather than the exported sendmail(), so that
2074 # nothing is imported into this package
2075 51 Email::Sender::Simple->send($email, { transport => $transport });
2076 58 };
2077  
2078 # async: send from a child process, so that the log call doesn't wait
2079 # for the SMTP conversation. Windows' fork is emulated with threads,
2080 # and while perl is exiting (DESTROY's flush) the modules may be gone
2081 58 ▶ if($sm->{'async'} && ($^O ne 'MSWin32') && (${^GLOBAL_PHASE} ne 'DESTRUCT')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sm->{"async"} and $^O ne "MSWin32" and ${^GLOBAL_PHASE} ne "DESTRUCT") 7 51 58
Condition66%4/6
$sm->{"async"} and $^O ne "MSWin32" and ${^GLOBAL_PHASE} ne "DESTRUCT"
!ll&&!rl&&r
5107
$sm->{"async"} and $^O ne "MSWin32"
!ll&&!rl&&r
5107
MC/DC33%1/3
$sm->{"async"} and $^O ne "MSWin32" and ${^GLOBAL_PHASE} ne "DESTRUCT"
$sm->{"async"} $^O ne "MSWin32" ${^GLOBAL_PHASE} ne "DESTRUCT"
Truth table50%2/4
A and B and C
A= $sm->{"async"}B= $^O ne "MSWin32"C= ${^GLOBAL_PHASE} ne "DESTRUCT"
ABCresult
0XX0
10X0
1100
1111
2082 7 _reap_email_children();
2083 7 my $pid = do {
2084 42 ▶ no autodie qw(fork);
Subroutine BEGIN: called CC=1 SCAR=0.0
2085 7 fork();
2086 };
2087 7 ▶ if(defined($pid) && ($pid == 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pid and $pid == 0) 0 7 7
Condition33%1/3
defined $pid and $pid == 0
!ll&&!rl&&r
070
MC/DC0%0/2
defined $pid and $pid == 0
defined $pid $pid == 0
Truth table33%1/3
A and B
A= defined $pidB= $pid == 0
ABresult
0X0
100
111
2088 # The child: no END blocks, destructors or buffered output of
2089 # the parent's must run here, so leave with _exit
2090 0 my $ok = eval { $deliver->(); 1 };
2091 0 ▶ if(!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
2092 # Copied first: entering the eval clears $@
2093 0 my $error = $@;
2094 0 eval { Carp::carp("Failed to send email: $error") };
2095 }
2096 0 ▶ POSIX::_exit($ok ? $EXIT_SENT : $EXIT_FAILED);
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 0 0 0
2097 }
2098 7 ▶ if(defined($pid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pid) 7 0 7
2099 7 push @email_children, $pid;
2100 7 delete @{$self}{qw(_email_digest _email_digest_dropped)};
2101 7 $self->{_last_email_sent} = time();
2102 7 return 1;
2103 }
2104 # fork failed: send it here instead
2105 }
2106  
2107 51 ▶ if(!eval { $deliver->(); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { &$deliver(); 1 } }) 4 47 51
2108 4 Carp::carp("Failed to send email: $@");
2109 4 ▶ if($sm->{'digest'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sm->{"digest"}) 1 3 4
2110 1 $self->_hold_email($sm, $_) for @lines;
2111 }
2112 4 return 0;
2113 }
2114  
2115 # Record send time for the throttle on success
2116 47 delete @{$self}{qw(_email_digest _email_digest_dropped)};
2117 47 $self->{_last_email_sent} = time();
2118 47 return 1;
2119 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2120  
2121 # ---------------------------------------------------------------------------
2122 # _reap_email_children -- collect the async sendmail children that finished
2123 #
2124 # Purpose: Stop finished children from being left as zombies.
2125 # Entry: None.
2126 # Exit: Returns nothing.
2127 # Side effects: Reaps, without waiting, the children in @email_children
2128 # that have exited, and forgets them. One already reaped by
2129 # the program (e.g. by a SIGCHLD handler) is forgotten too.
2130 # Notes: Called before each async send and by DESTROY. Children
2131 # still running then are reaped by a later call, or when the
2132 # program exits.
2133 # ---------------------------------------------------------------------------
2134 11 ▶sub _reap_email_children :Private {
Subroutine _reap_email_children: called CC=1 SCAR=0.0
2135 11 @email_children = grep { waitpid($_, POSIX::WNOHANG()) == 0 } @email_children;
2136 11 return;
2137 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2138  
2139 # ---------------------------------------------------------------------------
2140 # _hold_email -- keep a message body for the next email (sendmail digest)
2141 #
2142 # Purpose: With digest, messages that min_interval (or a failed send)
2143 # would lose are sent with the next email instead.
2144 # Entry: $self -- the logger object.
2145 # $sm -- the sendmail hash (digest_max).
2146 # $line -- the message's email body.
2147 # Exit: Returns nothing. Holds $line, or once digest_max are held,
2148 # only counts it, so a burst can't use unbounded memory.
2149 # ---------------------------------------------------------------------------
2150 128 ▶sub _hold_email :Private {
Subroutine _hold_email: called CC=4 SCAR=13.9
2151 128 my ($self, $sm, $line) = @_;
2152  
2153 128 ▶ my $held = $self->{_email_digest} ||= [];
Condition100%2/2
$self->{"_email_digest"} ||= []
l!l
11315
MC/DC100%1/1
$self->{"_email_digest"} ||= []
$self->{"_email_digest"}
Truth table100%2/2
A
A= $self->{"_email_digest"}
Aresult
11
00
2154 128 ▶ if(scalar(@{$held}) < ($sm->{'digest_max'} // $DEFAULT_DIGEST_MAX)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$held;} < ($sm->{'digest_max'} // $DEFAULT_DIGEST_MAX)) { } 120 8 128
Condition66%2/3
$sm->{"digest_max"} // $DEFAULT_DIGEST_MAX
l!l&&r!l&&!r
81200
MC/DC0%0/2
$sm->{"digest_max"} // $DEFAULT_DIGEST_MAX
$sm->{"digest_max"} $DEFAULT_DIGEST_MAX
Truth table66%2/3
A // B
A= $sm->{"digest_max"}B= $DEFAULT_DIGEST_MAX
ABresult
1X1
011
000
2155 120 push @{$held}, $line;
2156 } else {
2157 8 $self->{_email_digest_dropped}++;
2158 }
2159 128 return;
2160 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2161  
2162 # ---------------------------------------------------------------------------
2163 # _validate_file_path -- validate and untaint a filesystem path
2164 #
2165 # Purpose: Ensure a caller-supplied path does not contain dangerous
2166 # characters or directory-traversal sequences before it is
2167 # passed to open().
2168 # Entry: $self -- the logger object (for error context in croak).
2169 # $path -- the raw path string to validate.
2170 # Exit: Returns the untainted capture (Perl taint-safe string).
2171 # Croaks with a descriptive message if validation fails.
2172 # Notes: Blocks the character set <, >, |, *, ?, ;, !, `, $, "
2173 # and all C0 control characters, as well as ".." sequences.
2174 # ---------------------------------------------------------------------------
2175 184 ▶sub _validate_file_path :Private {
Subroutine _validate_file_path: called CC=3 SCAR=11.0
2176 184 my ($self, $path) = @_;
2177  
2178 # Block ".." path-traversal and all dangerous shell metacharacters
2179 184 ▶ if($path =~ $RE_SAFE_PATH && $path !~ $RE_DOTDOT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /$RE_SAFE_PATH/ and not $path =~ /$RE_DOTDOT/) 156 28 184
Condition100%3/3
$path =~ /$RE_SAFE_PATH/ and not $path =~ /$RE_DOTDOT/
!ll&&!rl&&r
235156
MC/DC100%2/2
$path =~ /$RE_SAFE_PATH/ and not $path =~ /$RE_DOTDOT/
$path =~ /$RE_SAFE_PATH/ not $path =~ /$RE_DOTDOT/
Truth table100%3/3
A and not(B)
A= $path =~ /$RE_SAFE_PATH/B= not $path =~ /$RE_DOTDOT/
ABresult
0X0
100
111
2180 156 return $1; # $1 is the untainted capture from RE_SAFE_PATH
2181 }
2182 28 Carp::croak(ref($self), ": Invalid file name: $path");
2183 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2184  
2185 # ---------------------------------------------------------------------------
2186 # _format_message -- expand a log-format string into a final log line
2187 #
2188 # Purpose: Centralise the repeated format-token substitution so that
2189 # file, fd, and scalar-path backends all share one code path.
2190 # Entry: $self -- the logger object (source of 'format' setting).
2191 # $level -- log level string (e.g. 'debug').
2192 # $str -- the already-joined message string.
2193 # $use_class -- 1 to include %class% in the default format,
2194 # 0 to use the no-class format.
2195 # $caller_file -- pre-resolved source file of the logging call.
2196 # $caller_line -- pre-resolved source line of the logging call.
2197 # $fields -- optional hashref of structured fields.
2198 # $timestamp -- the formatted time of the log call, from
2199 # _timestamp (computed here if undef).
2200 # $format -- the backend's own format, or undef for the
2201 # logger's 'format' (or the default).
2202 # Exit: Returns the formatted log line (without trailing newline).
2203 # Notes: %env_FOO% tokens are expanded with a // '' fallback so that
2204 # missing environment variables expand silently to empty string.
2205 # caller_file/caller_line are computed by _log at the correct
2206 # stack depth (adjusted for the extra _high_priority frame on
2207 # warn/error calls) so the reported location is always the
2208 # caller's code, not an internal dispatch frame.
2209 #
2210 # Pseudocode:
2211 # FUNCTION _format_message(self, level, str, use_class, caller_file, caller_line, fields, timestamp, format)
2212 # timestamp = timestamp // _timestamp()
2213 # format = format // self->{'format'}
2214 # IF format eq 'json':
2215 # Build hash: timestamp, level, message, file=caller_file, line=caller_line
2216 # (+ class if subclass)
2217 # (+ fields, with blessed values stringified, if any)
2218 # RETURN _to_json(\%hash)
2219 # [single compact line, character string, sorted keys]
2220 #
2221 # Choose default format template:
2222 # use_class=1 β†’ DEFAULT_FORMAT (includes %class%)
2223 # use_class=0 β†’ DEFAULT_FORMAT_NOCLASS
2224 # Override with format if one was supplied (non-empty)
2225 #
2226 # Compute token values:
2227 # message = str, plus the fields as logfmt key=value pairs if any,
2228 # with each embedded line break followed by a tab, so
2229 # continuation lines can't pass as new log entries
2230 # ulevel = uc(level)
2231 # class = blessed class if it is a subclass, else '' (base package)
2232 # callstack = caller_file and caller_line
2233 # timestamp = the timestamp argument
2234 #
2235 # Expand tokens in format string in a single pass (substituted values,
2236 # including the message, are never rescanned for further tokens):
2237 # %level% β†’ ulevel
2238 # %class% β†’ class (may be empty)
2239 # %message% β†’ message
2240 # %callstack% β†’ callstack
2241 # %timestamp% β†’ timestamp
2242 # %env_FOO% β†’ $ENV{FOO} // '' (silent if env var unset)
2243 #
2244 # RETURN formatted line string
2245 # END FUNCTION
2246 # ---------------------------------------------------------------------------
2247 250 ▶sub _format_message :Private {
Subroutine _format_message: called CC=17 SCAR=28.4
2248 250 my ($self, $level, $str, $use_class, $caller_file, $caller_line, $fields, $timestamp, $format) = @_;
2249  
2250 250 ▶ $timestamp //= $self->_timestamp();
Condition66%2/3
$timestamp //= $self->_timestamp
l!l&&r!l&&!r
24820
MC/DC0%0/2
$timestamp //= $self->_timestamp
$timestamp $self->_timestamp
Truth table66%2/3
A //= B
A= $timestampB= $self->_timestamp
ABresult
1X1
011
000
2251 250 ▶ $format //= $self->{'format'};
Condition100%3/3
$format //= $self->{"format"}
l!l&&r!l&&!r
2715964
MC/DC100%2/2
$format //= $self->{"format"}
$format $self->{"format"}
Truth table100%3/3
A //= B
A= $formatB= $self->{"format"}
ABresult
1X1
011
000
2252  
2253 # 'json' is a magic format value: emit a compact JSON object per line
2254 250 ▶ if(defined($format) && ($format eq 'json')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $format and $format eq "json") 29 221 250
Condition100%3/3
defined $format and $format eq "json"
!ll&&!rl&&r
6415729
MC/DC100%2/2
defined $format and $format eq "json"
defined $format $format eq "json"
Truth table100%3/3
A and B
A= defined $formatB= $format eq "json"
ABresult
0X0
100
111
2255 29 my $bclass = Scalar::Util::blessed($self);
2256 29 ▶ my $class = ($bclass && $bclass ne __PACKAGE__) ? $bclass : undef;
Branch: 1 branch
BranchTrueFalseTotal
$bclass && $bclass ne __PACKAGE__ ? : 2 27 29
Condition66%2/3
$bclass and $bclass ne __PACKAGE__
!ll&&!rl&&r
0272
MC/DC50%1/2
$bclass and $bclass ne __PACKAGE__
$bclass $bclass ne __PACKAGE__
Truth table66%2/3
A and B
A= $bclassB= $bclass ne __PACKAGE__
ABresult
0X0
100
111
2257 29 my %obj = (
2258 timestamp => $timestamp,
2259 level => $level,
2260 message => $str,
2261 file => $caller_file,
2262 line => $caller_line + 0,
2263 );
2264 29 ▶ $obj{class} = $class if defined($class);
Branch: 1 branch
BranchTrueFalseTotal
if defined $class 2 27 29
2265 29 ▶ if($fields) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fields) 14 15 29
2266 # Stringify objects, which would otherwise be encoded as null
2267 $obj{fields} = {
2268 14 ▶ map { $_ => (Scalar::Util::blessed($fields->{$_}) ? "$fields->{$_}" : $fields->{$_}) } keys %{$fields}
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($fields->{$_}) ? : 2 14 16
2269 };
2270 }
2271 # Characters out (not UTF-8 bytes): _write_line does the encoding
2272 29 return _to_json(\%obj);
2273 }
2274  
2275 # Select the appropriate default when no custom format is configured ('' is falsy)
2276 221 ▶ my $default = $use_class ? $DEFAULT_FORMAT : $DEFAULT_FORMAT_NOCLASS;
Branch: 1 branch
BranchTrueFalseTotal
$use_class ? : 11 210 221
2277 221 ▶ $format = $format || $default;
Condition66%2/3
$format || $default
l!l&&r!l&&!r
155660
MC/DC0%0/2
$format || $default
$format $default
Truth table66%2/3
A || B
A= $formatB= $default
ABresult
1X1
011
000
2278  
2279 221 my $ulevel = uc($level);
2280  
2281 # Suppress the class name for the base package (only show for subclasses)
2282 221 my $bclass = Scalar::Util::blessed($self);
2283 221 ▶ my $class = ($bclass && $bclass ne __PACKAGE__) ? $bclass : '';
Branch: 1 branch
BranchTrueFalseTotal
$bclass && $bclass ne __PACKAGE__ ? : 4 217 221
Condition66%2/3
$bclass and $bclass ne __PACKAGE__
!ll&&!rl&&r
02174
MC/DC50%1/2
$bclass and $bclass ne __PACKAGE__
$bclass $bclass ne __PACKAGE__
Truth table66%2/3
A and B
A= $bclassB= $bclass ne __PACKAGE__
ABresult
0X0
100
111
2284  
2285 # Indent continuation lines so that a message such as
2286 # "a\nERROR> [...] forged" can't pass as a separate log entry
2287 221 ▶ my $message = $fields ? join(' ', grep { length } $str, _fields_text($fields)) : $str;
Branch: 1 branch
BranchTrueFalseTotal
$fields ? : 9 212 221
2288 221 $message =~ s/\r\n?|\n/\n\t/g;
2289  
2290 221 my $callstack = "$caller_file $caller_line";
2291  
2292 221 my %tokens = (
2293 level => $ulevel,
2294 class => $class,
2295 message => $message,
2296 callstack => $callstack,
2297 timestamp => $timestamp,
2298 );
2299  
2300 # Expand all tokens in one pass so substituted text (notably the message)
2301 # is never rescanned; otherwise a message containing "%env_SECRET%" would
2302 # leak the environment variable into the log
2303 221 $format =~ s/%(?:(level|class|message|callstack|timestamp)|env_(\w+))%/
2304 448 ▶ defined($1) ? $tokens{$1} : ($ENV{$2} \/\/ '')/gex;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 439 9 448
Condition100%2/2
$ENV{$2} // ""
l!l
72
MC/DC100%1/1
$ENV{$2} // ""
$ENV{$2}
Truth table100%2/2
A
A= $ENV{$2}
Aresult
11
00
2305  
2306 221 return $format;
2307 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2308  
2309 # ---------------------------------------------------------------------------
2310 # _log -- central dispatcher that routes a message to all active backends
2311 #
2312 # Purpose: Every public logging method ultimately calls _log. It checks
2313 # the current level threshold, records the message in the
2314 # internal history, then dispatches to the configured backend(s).
2315 # Entry: $self -- the logger object.
2316 # $level -- one of trace/debug/info/notice/warn/error/
2317 # critical/alert/emergency.
2318 # @messages -- one or more message strings (or a single arrayref),
2319 # optionally followed by a hashref of structured fields.
2320 # Exit: Returns nothing (void). Croaks on configuration errors.
2321 # Side effects: Appends to $self->{messages}. Passes the message to the
2322 # backends (Log::Abstraction::Backend::*), which may write to a
2323 # file, fd, array, syslog, journald, email, Log::Any or
2324 # Log::Dispatch. May load Email::* modules.
2325 # Notes: Enforced private: croaks if called from outside this package.
2326 # The caller file/line is resolved past the _high_priority frame
2327 # (warn/error) and any Log::Any frames, so it is the user's code.
2328 #
2329 # Pseudocode:
2330 # FUNCTION _log(self, level, messages...)
2331 # CROAK if caller package is not this package (private method guard)
2332 # CROAK if level is not a recognised syslog level name
2333 # RETURN early if syslog_values{level} > self->{'level'} (below threshold)
2334 #
2335 # IF more than one argument AND the last is an unblessed hashref:
2336 # Pop it as the structured fields (a shallow copy; undef if empty)
2337 # Flatten single-arrayref argument to a list; filter out undefs; join to $str
2338 # IF redact: _redact $str (the parts become just $str) and the fields
2339 # $text = $str plus the fields as logfmt key=value pairs (for backends
2340 # with no field support: syslog, email, objects)
2341 # Push { level, message, fields? } onto self->{messages} (always recorded);
2342 # drop the oldest entries beyond max_messages
2343 # Set $class = '' for base package, else the blessed class name
2344 # Resolve caller file/line; format the timestamp once (_timestamp),
2345 # shared by every file/fd backend
2346 # render(format) = _format_message(..., format), cached per format;
2347 # undef format means the logger's own
2348 # Build the event: level, priority, message, parts, fields, text, the
2349 # history entry, class, caller file/line, ctx, and closures for the
2350 # private methods the backends need (render, write, send_email,
2351 # hold_email, field_string)
2352 # backends = self->{_backends}, or _build_backends() if not built yet
2353 # FOR each backend (see _build_backends for which and in what order):
2354 # IF backend->wants(event) (its own level, if any, lets it through):
2355 # backend->emit(self, event)
2356 # (each Log::Abstraction::Backend::* class documents what it does)
2357 # END FUNCTION
2358 # ---------------------------------------------------------------------------
2359 11319 ▶sub _log :Private {
Subroutine _log: called CC=29 SCAR=33.8
2360 11319 my ($self, $level, @messages) = @_;
2361  
2362 # Reject direct calls from outside this package (also enforced by :Private)
2363 11319 ▶ if(!(caller)[0]->isa(__PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ((&CORE::GLOBAL::caller())[0]->isa(__PACKAGE__)) 2 11317 11319
2364 2 Carp::croak('Illegal Operation: _log is a private method');
2365 }
2366  
2367 # Logging must not disturb the caller's error state: code such as
2368 # eval { ... }; if($@) { $log->debug(...); die $@ } relies on it, and
2369 # the backends' own evals and I/O would otherwise reset $@ and $!
2370 11317 local ($@, $!);
2371  
2372 # Sanity-check the level (should not be reachable in normal use)
2373 11317 ▶ if(!defined($syslog_values{$level})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Log::Abstraction::syslog_values{$level}) 0 11317 11317
2374 0 Carp::croak(ref($self), ": Invalid level '$level'");
2375 }
2376  
2377 # Drop messages that fall below the configured threshold
2378 11317 ▶ if($syslog_values{$level} > $self->{'level'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Log::Abstraction::syslog_values{$level} > $self->{"level"}) 188 11129 11317
2379 188 return;
2380 }
2381  
2382 # A trailing hashref after the message holds structured fields, e.g.
2383 # $log->info('login', { user_id => 42 }). Copy it so that the caller
2384 # changing it later doesn't rewrite the history
2385 11129 my $fields;
2386 11129 ▶ if((scalar(@messages) > 1) && (ref($messages[-1]) eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @messages > 1 and ref $messages[-1] eq "HASH") 60 11069 11129
Condition100%3/3
scalar @messages > 1 and ref $messages[-1] eq "HASH"
!ll&&!rl&&r
110521760
MC/DC100%2/2
scalar @messages > 1 and ref $messages[-1] eq "HASH"
scalar @messages > 1 ref $messages[-1] eq "HASH"
Truth table100%3/3
A and B
A= scalar @messages > 1B= ref $messages[-1] eq "HASH"
ABresult
0X0
100
111
2387 60 $fields = pop @messages;
2388 60 ▶ $fields = %{$fields} ? { %{$fields} } : undef;
Branch: 1 branch
BranchTrueFalseTotal
%{$fields;} ? : 59 1 60
2389 }
2390  
2391 # Flatten a single arrayref argument to a plain list
2392 11129 ▶ if((scalar(@messages) == 1) && (ref($messages[0]) eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @messages == 1 and ref $messages[0] eq "ARRAY") 6 11123 11129
Condition100%3/3
scalar @messages == 1 and ref $messages[0] eq "ARRAY"
!ll&&!rl&&r
19111046
MC/DC100%2/2
scalar @messages == 1 and ref $messages[0] eq "ARRAY"
scalar @messages == 1 ref $messages[0] eq "ARRAY"
Truth table100%3/3
A and B
A= scalar @messages == 1B= ref $messages[0] eq "ARRAY"
ABresult
0X0
100
111
2393 6 @messages = @{$messages[0]};
2394 }
2395  
2396 # Remove any undef elements before joining
2397 11129 @messages = grep { defined } @messages;
2398 11129 my $str = join('', @messages);
2399 11129 chomp($str);
2400  
2401 # Redact before the message reaches the history or any backend. The
2402 # regex runs over the joined message, so a match may span arguments;
2403 # the CODE and object backends then get the one redacted string
2404 11129 ▶ if(my $redact = $self->{'redact'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $redact = $self->{"redact"}) 26 11103 11129
2405 26 $str = _redact($redact, $str);
2406 26 @messages = ($str);
2407 26 ▶ $fields = _redact($redact, $fields) if($fields);
Branch: 1 branch
BranchTrueFalseTotal
if $fields 9 17 26
2408 }
2409  
2410 # Backends with no notion of fields get them appended as text
2411 11129 ▶ my $fields_text = $fields ? _fields_text($fields) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$fields ? : 59 11070 11129
2412 11129 ▶ my $text = $fields ? join(' ', grep { length } $str, $fields_text) : $str;
Branch: 1 branch
BranchTrueFalseTotal
$fields ? : 59 11070 11129
2413  
2414 # The entry recorded by the history and the array backends
2415 11129 ▶ my @entry = (level => $level, message => $str, ($fields ? (fields => $fields) : ()));
Branch: 1 branch
BranchTrueFalseTotal
$fields ? : 59 11070 11129
2416  
2417 # Record in the internal message history regardless of backend,
2418 # discarding the oldest entries beyond max_messages
2419 11129 my $history = $self->{messages};
2420 11129 push @{$history}, { @entry };
2421 11129 ▶ if(defined(my $max = $self->{'max_messages'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $max = $self->{"max_messages"})) 14 11115 11129
2422 14 ▶ splice(@{$history}, 0, scalar(@{$history}) - $max) if(scalar(@{$history}) > $max);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$history;} > $max 9 5 14
2423 }
2424  
2425 # Compute class once; suppress the package name for base-class instances
2426 11129 ▶ my $class = Scalar::Util::blessed($self) || $self;
Condition33%1/3
builtin::blessed($self) || $self
l!l&&r!l&&!r
1112900
MC/DC0%0/2
builtin::blessed($self) || $self
builtin::blessed($self) $self
Truth table33%1/3
A || B
A= builtin::blessed($self)B= $self
ABresult
1X1
011
000
2427 11129 ▶ if($class eq __PACKAGE__) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class eq __PACKAGE__) 11123 6 11129
2428 11123 $class = '';
2429 }
2430  
2431 # Resolve caller file/line at the correct stack depth.
2432 # For trace/debug/info/notice: _log ← public_method ← user β†’ depth=1
2433 # For warn/error: _log ← _high_priority ← public_method ← user β†’ depth=2
2434 # Frames inside Log::Any (its proxy and our adapter) are skipped too, so
2435 # messages routed through Log::Any report the user's code. So are those
2436 # of the Log::Abstraction that forwarded a message here (see the LogAny
2437 # and LogDispatch backends)
2438 11129 ▶ my $depth = ((caller(1))[3] // '') =~ /::_high_priority$/ ? 2 : 1;
Branch: 1 branch
BranchTrueFalseTotal
((&CORE::GLOBAL::caller(1))[3] // '') =~ /::_high_priority$/ ? : 460 10669 11129
Condition50%1/2
(&CORE::GLOBAL::caller(1))[3] // ""
l!l
111290
MC/DC0%0/1
(&CORE::GLOBAL::caller(1))[3] // ""
(&CORE::GLOBAL::caller(1))[3]
Truth table50%1/2
A
A= (&CORE::GLOBAL::caller(1))[3]
Aresult
11
00
2439 11129 ▶ my $skip = $Log::Abstraction::Backend::FORWARDING ? qr/^Log::(?:Any|Abstraction|Dispatch)(?:::|$)/ : qr/^Log::Any(?:::|$)/;
Branch: 1 branch
BranchTrueFalseTotal
$Log::Abstraction::Backend::FORWARDING ? : 7 11122 11129
2440 11129 ▶ while((caller($depth + 1))[0] && (((caller($depth))[0] // '') =~ $skip)) {
Branch: 1 branch
BranchTrueFalseTotal
if ((&CORE::GLOBAL::caller($depth + 1))[0] and ((&CORE::GLOBAL::caller($depth))[0] // "") =~ /$skip/) 144 11129 11273
Condition80%4/5
(&CORE::GLOBAL::caller($depth + 1))[0] and ((&CORE::GLOBAL::caller($depth))[0] // "") =~ /$skip/
!ll&&!rl&&r
2811101144
(&CORE::GLOBAL::caller($depth))[0] // ""
l!l
112450
MC/DC50%1/2
(&CORE::GLOBAL::caller($depth + 1))[0] and ((&CORE::GLOBAL::caller($depth))[0] // "") =~ /$skip/
(&CORE::GLOBAL::caller($depth + 1))[0] (&CORE::GLOBAL::caller($depth))[0]
Truth table66%2/3
A and B
A= (&CORE::GLOBAL::caller($depth + 1))[0]B= (&CORE::GLOBAL::caller($depth))[0]
ABresult
0X0
100
111
2441 144 $depth++;
2442 }
2443 11129 my $caller_file = (caller($depth))[1];
2444 11129 my $caller_line = (caller($depth))[2];
2445  
2446 # One timestamp per message, so that every backend shows the same time
2447 11129 my $timestamp = $self->_timestamp();
2448  
2449 # Format the message for a backend: $format is its own format, or undef
2450 # for the logger's. Each format is only rendered once per message
2451 11129 ▶ my $use_class = ($class ne '') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$class ne '' ? : 6 11123 11129
2452 11129 my %rendered;
2453 245 ▶ my $render = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
2454 245 my ($format) = @_;
2455 245 ▶ return $rendered{$format // ''} //= $self->_format_message(
Condition80%4/5
$rendered{$format // ""} //= $self->_format_message($level, $str, $use_class, $caller_file, $caller_line, $fields, $timestamp, $format)
l!l&&r!l&&!r
72380
$format // ""
l!l
16229
MC/DC0%0/2
$rendered{$format // ""} //= $self->_format_message($level, $str, $use_class, $caller_file, $caller_line, $fields, $timestamp, $format)
$rendered{$format // ""} $self->_format_message($level, $str, $use_class, $caller_file, $caller_line, $fields, $timestamp, $format)
MC/DC100%1/1
$format // ""
$format
Truth table66%2/3
A //= B
A= $rendered{$format // ""}B= $self->_format_message($level, $str, $use_class, $caller_file, $caller_line, $fields, $timestamp, $format)
ABresult
1X1
011
000
Truth table100%2/2
A
A= $format
Aresult
11
00
2456 $level, $str, $use_class, $caller_file, $caller_line, $fields, $timestamp, $format,
2457 );
2458 11129 };
2459  
2460 # What a backend needs to know about the message, and closures for
2461 # the private methods it needs (see Log::Abstraction::Backend)
2462 my %event = (
2463 level => $level,
2464 priority => $syslog_values{$level},
2465 message => $str,
2466 parts => \@messages,
2467 fields => $fields,
2468 fields_text => $fields_text,
2469 text => $text,
2470 entry => \@entry,
2471 class => Scalar::Util::blessed($self) || __PACKAGE__,
2472 file => $caller_file,
2473 line => $caller_line,
2474 ctx => $self->{ctx},
2475 render => $render,
2476 231 ▶ write => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2477 231 my ($target, $line) = @_;
2478 231 ▶ $target = $self->_validate_file_path($target) if(!ref($target));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $target 168 63 231
2479 218 $self->_write_line($target, $line);
2480 },
2481 61 ▶ send_email => sub { $self->_send_email(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2482 127 ▶ hold_email => sub { $self->_hold_email(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2483 16 ▶ field_string => sub { _field_string(@_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
2484 11129 ▶ );
Condition50%1/2
builtin::blessed($self) || __PACKAGE__
l!l
111290
MC/DC0%0/1
builtin::blessed($self) || __PACKAGE__
builtin::blessed($self)
Truth table50%1/2
A
A= builtin::blessed($self)
Aresult
11
00
2485  
2486 # Pass the message to every backend whose own level it passes. A bare
2487 # object (not made by new()) builds them now
2488 11129 ▶ my $backends = $self->{_backends} //= $self->_build_backends();
Condition66%2/3
$self->{"_backends"} //= $self->_build_backends
l!l&&r!l&&!r
1112720
MC/DC0%0/2
$self->{"_backends"} //= $self->_build_backends
$self->{"_backends"} $self->_build_backends
Truth table66%2/3
A //= B
A= $self->{"_backends"}B= $self->_build_backends
ABresult
1X1
011
000
2489 11129 for my $backend (@{$backends}) {
2490 11431 ▶ $backend->emit($self, \%event) if($backend->wants(\%event));
Branch: 1 branch
BranchTrueFalseTotal
if $backend->wants(\%event) 11397 34 11431
2491 }
2492 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2493  
2494 # ---------------------------------------------------------------------------
2495 # _high_priority -- common handler for warn(), error() and the levels above
2496 #
2497 # Purpose: Extracts the warning/error text from a variety of argument
2498 # forms (plain list, named 'warning' key, or arrayref value),
2499 # then dispatches to _log and optionally to Carp.
2500 # Entry: $self -- the logger object.
2501 # $level -- 'warn', 'error', 'critical', 'alert' or 'emergency'.
2502 # @_ -- remaining arguments in any of the accepted forms.
2503 # Exit: Returns nothing (void).
2504 # Side effects: Calls _log, which appends to $self->{messages} and writes to
2505 # configured backends. May call Carp::carp or Carp::croak.
2506 # Notes: The duplicated extraction logic that appeared in earlier
2507 # versions has been collapsed into a single if/else block.
2508 #
2509 # Pseudocode:
2510 # FUNCTION _high_priority(self, level, args...)
2511 # RETURN early if no args supplied
2512 #
2513 # IF more than one arg AND the last is an unblessed hashref:
2514 # Pop it as the structured fields
2515 #
2516 # Attempt to parse args as named-parameter form via Params::Get (in eval)
2517 #
2518 # IF named 'warning' key found in result:
2519 # Extract warning value; RETURN if value is undef
2520 # IF value is an arrayref: join defined elements into a string
2521 # ELSE (plain list form):
2522 # Join defined elements of @_ into a string
2523 # RETURN if resulting string is empty
2524 #
2525 # IF called as a class method (self is a package name, not an object):
2526 # IF error level or above: CROAK with warning text; RETURN
2527 # CARP with warning text; RETURN
2528 #
2529 # Call self->_log(level, warning, fields?)
2530 # IF redact: _redact the warning text, for Carp below
2531 #
2532 # no_backend = no logger, array, file or fd configured
2533 #
2534 # IF error level or above:
2535 # IF croak_on_error flag set OR no_backend:
2536 # CROAK with warning text
2537 #
2538 # IF (carp_on_warn flag set OR no_backend) AND level passes threshold:
2539 # CARP with warning text
2540 # END FUNCTION
2541 # ---------------------------------------------------------------------------
2542 489 ▶sub _high_priority :Private {
Subroutine _high_priority: called CC=22 SCAR=30.9
2543 489 my $self = shift;
2544 489 my $level = shift; # 'warn', 'error', 'critical', 'alert' or 'emergency'
2545  
2546 # Preserve the caller's $@ and $! (see _log); a croak from here still
2547 # reaches the caller, as die sets $@ after the stack has unwound
2548 489 local ($@, $!);
2549  
2550 # Nothing to log if no arguments supplied
2551 489 ▶ return if(scalar(@_) == 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ == 0 1 488 489
2552  
2553 # A trailing hashref after the message holds structured fields. A lone
2554 # hashref is the warn({ warning => ... }) form, not fields
2555 488 my @fields;
2556 488 ▶ if((scalar(@_) > 1) && (ref($_[-1]) eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ > 1 and ref $_[-1] eq "HASH") 19 469 488
Condition100%3/3
scalar @_ > 1 and ref $_[-1] eq "HASH"
!ll&&!rl&&r
4402919
MC/DC100%2/2
scalar @_ > 1 and ref $_[-1] eq "HASH"
scalar @_ > 1 ref $_[-1] eq "HASH"
Truth table100%3/3
A and B
A= scalar @_ > 1B= ref $_[-1] eq "HASH"
ABresult
0X0
100
111
2557 19 @fields = (pop @_);
2558 }
2559  
2560 # Try to interpret arguments as warn(warning => VALUE) named form
2561 488 my $params;
2562 488 eval { $params = Params::Get::get_params('warning', @_) };
2563  
2564 # Determine the final warning string from whichever form was passed
2565 488 my $warning;
2566 488 ▶ if($params && ref($params) eq 'HASH' && exists($params->{warning})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params and ref $params eq 'HASH' and exists $params->{'warning'}) { } 480 8 488
Condition83%5/6
$params and ref $params eq "HASH" and exists $params->{"warning"}
!ll&&!rl&&r
35480
$params and ref $params eq "HASH"
!ll&&!rl&&r
30485
MC/DC66%2/3
$params and ref $params eq "HASH" and exists $params->{"warning"}
$params ref $params eq "HASH" exists $params->{"warning"}
Truth table75%3/4
A and B and C
A= $paramsB= ref $params eq "HASH"C= exists $params->{"warning"}
ABCresult
0XX0
10X0
1100
1111
2567 # Named form: warn({ warning => ... }) or warn(warning => ...)
2568 480 $warning = $params->{warning};
2569 480 ▶ return unless defined($warning);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $warning 2 478 480
2570 478 ▶ if(ref($warning) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $warning eq "ARRAY") 13 465 478
2571 # Arrayref value: join defined elements
2572 13 $warning = join('', grep { defined } @{$warning});
2573 }
2574 } else {
2575 # Plain list form: warn('text', 'more text', ...)
2576 8 $warning = join('', grep { defined } @_);
2577 8 ▶ return unless length($warning);
Branch: 1 branch
BranchTrueFalseTotal
unless length $warning 0 8 8
2578 }
2579  
2580 # If called as a class method (on this package or a subclass) rather
2581 # than on an instance, use Carp directly
2582 486 ▶ if(!ref($self)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 9 477 486
2583 9 ▶ if($syslog_values{$level} <= $ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Log::Abstraction::syslog_values{$level} <= $Log::Abstraction::ERROR) 6 3 9
2584 6 Carp::croak($warning);
2585 }
2586 3 Carp::carp($warning);
2587 3 return;
2588 }
2589  
2590 # Log the message through the normal dispatch path
2591 477 $self->_log($level, $warning, @fields);
2592  
2593 # What Carp shows must be redacted too (_log redacts its own copy)
2594 468 ▶ $warning = _redact($self->{'redact'}, $warning) if($self->{'redact'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"redact"} 3 465 468
2595  
2596 # A top-level file or fd counts as a backend, as do logger and array
2597 my $no_backend = !defined($self->{'logger'}) && !defined($self->{'array'})
2598 468 ▶ && !$self->{'file'} && !$self->{'fd'};
Condition100%9/9
defined $self->{'logger'} || defined $self->{'array'} || $self->{'file'} || $self->{'fd'}
l!l&&r!l&&!r
46251
defined $self->{"logger"} or defined $self->{"array"} or $self->{"file"}
l!l&&r!l&&!r
46026
defined $self->{"logger"} or defined $self->{"array"}
l!l&&r!l&&!r
364968
MC/DC100%4/4
defined $self->{'logger'} || defined $self->{'array'} || $self->{'file'} || $self->{'fd'}
defined $self->{"logger"} defined $self->{"array"} $self->{"file"} $self->{'fd'}
Truth table100%5/5
A or B or C || D
A= defined $self->{"logger"}B= defined $self->{"array"}C= $self->{"file"}D= $self->{'fd'}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2599  
2600 # Optionally escalate to Carp for error-level messages
2601 468 ▶ if($syslog_values{$level} <= $ERROR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Log::Abstraction::syslog_values{$level} <= $Log::Abstraction::ERROR) 322 146 468
2602 322 ▶ if($self->{'croak_on_error'} || $no_backend) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"croak_on_error"} or $no_backend) 20 302 322
Condition100%3/3
$self->{"croak_on_error"} or $no_backend
l!l&&r!l&&!r
191302
MC/DC100%2/2
$self->{"croak_on_error"} or $no_backend
$self->{"croak_on_error"} $no_backend
Truth table100%3/3
A or B
A= $self->{"croak_on_error"}B= $no_backend
ABresult
1X1
011
000
2603 20 Carp::croak($warning);
2604 }
2605 }
2606  
2607 # Optionally also emit a Carp::carp, but only for a message that passed
2608 # the level threshold
2609 448 ▶ if(($self->{'carp_on_warn'} || $no_backend)
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"carp_on_warn"} || $no_backend and $Log::Abstraction::syslog_values{$level} <= $self->{"level"}) 12 436 448
Condition83%5/6
$self->{"carp_on_warn"} || $no_backend and $Log::Abstraction::syslog_values{$level} <= $self->{"level"}
!ll&&!rl&&r
435112
$self->{"carp_on_warn"} or $no_backend
l!l&&r!l&&!r
130435
MC/DC66%2/3
$self->{"carp_on_warn"} || $no_backend and $Log::Abstraction::syslog_values{$level} <= $self->{"level"}
$self->{"carp_on_warn"} $no_backend $Log::Abstraction::syslog_values{$level} <= $self->{"level"}
Truth table60%3/5
A or B and C
A= $self->{"carp_on_warn"}B= $no_backendC= $Log::Abstraction::syslog_values{$level} <= $self->{"level"}
ABCresult
00X0
1X00
0100
1X11
0111
2610 && ($syslog_values{$level} <= $self->{'level'})) {
2611 12 Carp::carp($warning);
2612 }
2613 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2614  
2615 =head2 level
2616  
2617 my $current = $logger->level();
2618 $logger->level('debug');
2619  
2620 Get or set the minimum logging level. When setting, returns C<$self> to
2621 allow method chaining. When getting, returns the current level as an
2622 integer (per the syslog numeric scale; lower numbers are higher priority).
2623  
2624 =head3 Arguments
2625  
2626 =over 4
2627  
2628 =item * C<$level> (optional)
2629  
2630 A level name string: C<trace>, C<debug>, C<info>, C<notice>, C<warn>/C<warning>,
2631 or C<error>. Case-insensitive. Omit to perform a pure get.
2632  
2633 =back
2634  
2635 =head3 Returns
2636  
2637 In getter mode: an integer in the range 0 (emergency) to 7 (debug/trace).
2638  
2639 In setter mode: C<$self> (to allow chaining), or C<undef>, after a
2640 C<Carp::carp>, if the level name is not recognised; the level is then
2641 unchanged. A false argument (C<undef>, C<''> or C<0>) is a get, not a set,
2642 so levels are set by name.
2643  
2644 =head3 Side Effects
2645  
2646 When setting, updates C<$self-E<gt>{level}>.
2647  
2648 =head3 Example
2649  
2650 $logger->level('debug');
2651 my $n = $logger->level(); # e.g. 7
2652  
2653 # Method chaining
2654 $logger->level('info')->info('Now at info level');
2655  
2656 =head3 API SPECIFICATION
2657  
2658 =head4 Input
2659  
2660 {
2661 level => { type => 'string', regex => qr/^(trace|debug|info(?:rmational)?|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|alert|emerg(?:ency)?|panic)$/i, optional => 1 },
2662 }
2663  
2664 =head4 Output
2665  
2666 Getter: { type => 'integer', min => 0, max => 7 }
2667 Setter: { type => 'object', class => 'Log::Abstraction' }
2668  
2669 =head3 MESSAGES
2670  
2671 Warning Meaning / Action
2672 ---------------------------------------- ------------------------------------------
2673 "<class>: invalid syslog level '<l>'" The supplied level name is not recognised.
2674 Use trace/debug/info/notice/warn/error.
2675  
2676 =head3 PSEUDOCODE
2677  
2678 FUNCTION level(self, level?)
2679  
2680 IF level argument supplied:
2681 CARP and RETURN undef if level is not a recognised syslog name
2682 Store syslog_values{level} in self->{'level'}
2683 RETURN self (allows method chaining)
2684  
2685 ELSE (getter mode):
2686 RETURN self->{'level'} (current numeric threshold)
2687  
2688 END FUNCTION
2689  
2690 =cut
2691  
2692 265 ▶sub level {
Subroutine level: called CC=3 SCAR=11.0
Pod documented
2693 265 my ($self, $level) = @_;
2694  
2695 265 ▶ if($level) {
Branch: 1 branch
BranchTrueFalseTotal
if ($level) 241 24 265
2696 # Setter path: validate, store and return $self for chaining.
2697 # Names are case-insensitive, as in new()
2698 241 ▶ if(!defined($syslog_values{lc($level)})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Log::Abstraction::syslog_values{lc $level}) 2 239 241
2699 2 Carp::carp(ref($self), ": invalid syslog level '$level'");
2700 2 return; # undef signals the caller that validation failed
2701 }
2702 239 $self->{'level'} = $syslog_values{lc($level)};
2703 239 return $self;
2704 }
2705  
2706 # Getter path: return the numeric threshold
2707 return Return::Set::set_return(
2708 24 $self->{'level'},
2709 { 'type' => 'integer', 'min' => 0, 'max' => 7 },
2710 );
2711 }
2712  
2713 =head2 Level detection methods
2714  
2715 =over 4
2716  
2717 =item is_trace
2718  
2719 =item is_debug
2720  
2721 =item is_info
2722  
2723 =item is_notice
2724  
2725 =item is_warn
2726  
2727 =item is_error
2728  
2729 =item is_critical
2730  
2731 =item is_alert
2732  
2733 =item is_emergency
2734  
2735 =back
2736  
2737 if($logger->is_debug()) { ... }
2738  
2739 Each returns a true value when a message logged with the method of the same
2740 name (C<is_warn> for C<warn()>) would pass the logger's level threshold, so
2741 that expensive message-building can be skipped. They follow the current
2742 threshold, including changes made with L</level>. As with the levels
2743 themselves, C<is_trace> equals C<is_debug>. Provided for compatibility with
2744 L<Log::Any>.
2745  
2746 =head3 Arguments
2747  
2748 None.
2749  
2750 =head3 Returns
2751  
2752 C<1> if messages at that level would be emitted; C<0> otherwise.
2753  
2754 =head3 Example
2755  
2756 if($logger->is_debug()) {
2757 $logger->debug('Expensive diagnostic: ' . Dumper(\%state));
2758 }
2759  
2760 $logger->level('warning');
2761 $logger->is_warn(); # 1
2762 $logger->is_info(); # 0
2763  
2764 =head3 API SPECIFICATION
2765  
2766 =head4 Input
2767  
2768 {} (no arguments)
2769  
2770 =head4 Output
2771  
2772 { type => 'boolean' }
2773  
2774 =cut
2775  
2776 # Build is_trace, is_debug, ... is_emergency. Each is true when its level's
2777 # syslog number is within the threshold (a lower number is more severe)
2778 42 for my $level (qw(trace debug info notice warn error critical alert emergency)) {
2779 378 my $threshold = $syslog_values{$level};
2780 42 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
2781 378 ▶ *{"is_$level"} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2782 327 my $self = $_[0];
2783 327 ▶ return (defined($self->{'level'}) && ($self->{'level'} >= $threshold)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $self->{'level'} && $self->{'level'} >= $threshold ? : 192 135 327
Condition66%2/3
defined $self->{"level"} and $self->{"level"} >= $threshold
!ll&&!rl&&r
0135192
MC/DC50%1/2
defined $self->{"level"} and $self->{"level"} >= $threshold
defined $self->{"level"} $self->{"level"} >= $threshold
Truth table66%2/3
A and B
A= defined $self->{"level"}B= $self->{"level"} >= $threshold
ABresult
0X0
100
111
2784 378 };
2785 }
2786  
2787 =head2 messages
2788  
2789 my $aref = $logger->messages();
2790  
2791 Returns a reference to a shallow copy of all messages emitted through this
2792 logger since it was created (or since the last clone).
2793  
2794 =head3 Arguments
2795  
2796 None.
2797  
2798 =head3 Returns
2799  
2800 An array reference of hashrefs, each with keys C<level> (string) and
2801 C<message> (string), and C<fields> (hashref) when the message was logged with
2802 L</Structured fields>.
2803  
2804 =head3 Side Effects
2805  
2806 None. The returned array is a copy; modifying it does not affect the
2807 internal history.
2808  
2809 =head3 Example
2810  
2811 $logger->info('hello');
2812 my $msgs = $logger->messages();
2813 # $msgs->[0] = { level => 'info', message => 'hello' }
2814  
2815 =head3 API SPECIFICATION
2816  
2817 =head4 Input
2818  
2819 {} (no arguments)
2820  
2821 =head4 Output
2822  
2823 { type => 'arrayref', element_type => { level => 'string', message => 'string', fields => 'hashref?' } }
2824  
2825 =cut
2826  
2827 84 ▶sub messages {
Subroutine messages: called CC=1 SCAR=0.0
Pod documented
2828 84 my $self = $_[0];
2829  
2830 84 return [ @{$self->{messages}} ];
2831 }
2832  
2833 =head2 flush
2834  
2835 $logger->flush();
2836  
2837 Sends, now, the messages that a C<sendmail> backend with C<digest> is
2838 holding back because of C<min_interval> (see L</Email digests>), whether or
2839 not the interval has passed. Does nothing if none are held. Called
2840 automatically when the logger is destroyed.
2841  
2842 =head3 Arguments
2843  
2844 None.
2845  
2846 =head3 Returns
2847  
2848 The logger, for method chaining.
2849  
2850 =head3 Side Effects
2851  
2852 May send an email, which starts the C<min_interval> interval again. A
2853 delivery failure is carped and the messages stay held. With C<async>, the
2854 email is sent by a child process and the messages are no longer held: a
2855 failure is carped by the child, and the messages are lost. Croaks if the
2856 C<sendmail> C<host> or C<port> is invalid.
2857  
2858 =head3 Example
2859  
2860 $logger->error('disk full'); # emailed
2861 $logger->error('disk still full'); # held: within min_interval
2862 $logger->flush(); # emailed now
2863  
2864 =head3 API SPECIFICATION
2865  
2866 =head4 Input
2867  
2868 {} (no arguments)
2869  
2870 =head4 Output
2871  
2872 { type => 'object', class => 'Log::Abstraction' }
2873  
2874 =cut
2875  
2876 9 ▶sub flush {
Subroutine flush: called CC=4 SCAR=13.9
Pod documented
2877 9 my $self = $_[0];
2878  
2879 # Preserve the caller's $@ and $! (see _log)
2880 9 local ($@, $!);
2881  
2882 9 ▶ my $sm = (ref($self->{'logger'}) eq 'HASH') ? $self->{'logger'}->{'sendmail'} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $self->{'logger'} eq 'HASH' ? : 8 1 9
2883 9 ▶ if($sm && $self->{_email_digest}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sm and $self->{"_email_digest"}) 5 4 9
Condition100%3/3
$sm and $self->{"_email_digest"}
!ll&&!rl&&r
135
MC/DC100%2/2
$sm and $self->{"_email_digest"}
$sm $self->{"_email_digest"}
Truth table100%3/3
A and B
A= $smB= $self->{"_email_digest"}
ABresult
0X0
100
111
2884 5 $self->_send_email($sm);
2885 }
2886 9 return $self;
2887 }
2888  
2889 =head2 reopen
2890  
2891 $logger->reopen();
2892  
2893 Closes the log files the logger holds open, so that the next message opens
2894 them again. Log files written by path (see L</File rotation>) are kept open
2895 between messages; call this after something outside the program has renamed,
2896 moved or truncated them. It isn't usually needed: a file that has been
2897 renamed or deleted is noticed on the next write, a C<SIGHUP> reopens every
2898 logger's files (except on Windows, see L</logrotate>), and every file is
2899 reopened when C<reopen_interval> has passed (unless it is C<-1>). File
2900 handles passed as C<fd> are not closed. It does nothing if no files are
2901 open.
2902  
2903 A file is also closed when writing to it fails (e.g. the disk is full), so
2904 that the next message opens it again.
2905  
2906 A program that sets its own C<$SIG{HUP}> after logging has started replaces
2907 the module's handler, and can call this from its own:
2908  
2909 $SIG{HUP} = sub { $logger->reopen(); reload_config() };
2910  
2911 =head3 Arguments
2912  
2913 None.
2914  
2915 =head3 Returns
2916  
2917 The logger, for method chaining.
2918  
2919 =head3 Side Effects
2920  
2921 Closes the logger's log files.
2922  
2923 =head3 API SPECIFICATION
2924  
2925 =head4 Input
2926  
2927 {} (no arguments)
2928  
2929 =head4 Output
2930  
2931 { type => 'object', class => 'Log::Abstraction' }
2932  
2933 =cut
2934  
2935 5 ▶sub reopen {
Subroutine reopen: called CC=1 SCAR=0.0
Pod documented
2936 5 my $self = $_[0];
2937  
2938 # Preserve the caller's $@ and $! (see _log)
2939 5 local ($@, $!);
2940  
2941 5 $self->_close_files();
2942 5 return $self;
2943 }
2944  
2945 =head2 trace
2946  
2947 $logger->trace(@messages);
2948 $logger->trace(\@messages);
2949  
2950 Logs a message at C<trace> level. syslog has no priority below debug, so
2951 C<trace> shares C<debug>'s threshold: trace messages are emitted whenever
2952 debug messages are, and are sent to syslog and journald as debug. The
2953 message is dropped silently when the configured level is above C<debug>.
2954  
2955 =head3 Arguments
2956  
2957 =over 4
2958  
2959 =item * C<@messages>
2960  
2961 One or more strings, or a single array reference. All elements are joined
2962 without a separator before storage. May be followed by a hashref of
2963 L</Structured fields>.
2964  
2965 =back
2966  
2967 =head3 Returns
2968  
2969 C<$self>, to allow method chaining.
2970  
2971 =head3 Side Effects
2972  
2973 Appends to the internal message history and dispatches to configured backends.
2974  
2975 =head3 Example
2976  
2977 $logger->trace('entering sub foo, args=', join(',', @args));
2978  
2979 # Chaining
2980 $logger->trace('start')->debug('details')->info('summary');
2981  
2982 =head3 API SPECIFICATION
2983  
2984 =head4 Input
2985  
2986 { messages => { type => [ 'arrayref', 'scalar' ] } }
2987  
2988 =head4 Output
2989  
2990 { type => 'object', class => 'Log::Abstraction' }
2991  
2992 =head3 MESSAGES
2993  
2994 Croaks if the configured backend is misconfigured, and carps if delivery
2995 fails; see the second table under L</new>'s MESSAGES.
2996  
2997 =cut
2998  
2999 34 ▶sub trace {
Subroutine trace: called CC=1 SCAR=0.0
Pod documented
3000 34 my $self = shift;
3001 34 $self->_log('trace', @_);
3002 34 return $self;
3003 }
3004  
3005 =head2 debug
3006  
3007 $logger->debug(@messages);
3008 $logger->debug(\@messages);
3009  
3010 Logs a message at C<debug> level.
3011  
3012 =head3 Arguments
3013  
3014 =over 4
3015  
3016 =item * C<@messages>
3017  
3018 One or more strings, or a single array reference, optionally followed by
3019 a hashref of L</Structured fields>.
3020  
3021 =back
3022  
3023 =head3 Returns
3024  
3025 C<$self>, to allow method chaining.
3026  
3027 =head3 Side Effects
3028  
3029 Appends to the internal message history and dispatches to configured backends.
3030  
3031 =head3 Example
3032  
3033 $logger->debug('Query took ', $elapsed, 'ms');
3034  
3035 =head3 API SPECIFICATION
3036  
3037 =head4 Input
3038  
3039 { messages => { type => [ 'arrayref', 'scalar' ] } }
3040  
3041 =head4 Output
3042  
3043 { type => 'object', class => 'Log::Abstraction' }
3044  
3045 =head3 MESSAGES
3046  
3047 Croaks if the configured backend is misconfigured, and carps if delivery
3048 fails; see the second table under L</new>'s MESSAGES.
3049  
3050 =cut
3051  
3052 10393 ▶sub debug {
Subroutine debug: called CC=1 SCAR=0.0
Pod documented
3053 10393 my $self = shift;
3054 10393 $self->_log('debug', @_);
3055 10377 return $self;
3056 }
3057  
3058 =head2 info
3059  
3060 $logger->info(@messages);
3061 $logger->info(\@messages);
3062  
3063 Logs a message at C<info> level.
3064  
3065 =head3 Arguments
3066  
3067 =over 4
3068  
3069 =item * C<@messages>
3070  
3071 One or more strings, or a single array reference, optionally followed by
3072 a hashref of L</Structured fields>.
3073  
3074 =back
3075  
3076 =head3 Returns
3077  
3078 C<$self>, to allow method chaining.
3079  
3080 =head3 Side Effects
3081  
3082 Appends to the internal message history and dispatches to configured backends.
3083  
3084 =head3 Example
3085  
3086 $logger->info('Server started on port ', $port);
3087  
3088 =head3 API SPECIFICATION
3089  
3090 =head4 Input
3091  
3092 { messages => { type => [ 'arrayref', 'scalar' ] } }
3093  
3094 =head4 Output
3095  
3096 { type => 'object', class => 'Log::Abstraction' }
3097  
3098 =head3 MESSAGES
3099  
3100 Croaks if the configured backend is misconfigured, and carps if delivery
3101 fails; see the second table under L</new>'s MESSAGES.
3102  
3103 =cut
3104  
3105 367 ▶sub info {
Subroutine info: called CC=1 SCAR=0.0
Pod documented
3106 367 my $self = shift;
3107 367 $self->_log('info', @_);
3108 367 return $self;
3109 }
3110  
3111 =head2 notice
3112  
3113 $logger->notice(@messages);
3114 $logger->notice(\@messages);
3115  
3116 Logs a message at C<notice> level (higher priority than C<info>, lower than
3117 C<warn>).
3118  
3119 =head3 Arguments
3120  
3121 =over 4
3122  
3123 =item * C<@messages>
3124  
3125 One or more strings, or a single array reference, optionally followed by
3126 a hashref of L</Structured fields>.
3127  
3128 =back
3129  
3130 =head3 Returns
3131  
3132 C<$self>, to allow method chaining.
3133  
3134 =head3 Side Effects
3135  
3136 Appends to the internal message history and dispatches to configured backends.
3137  
3138 =head3 Example
3139  
3140 $logger->notice('Configuration reloaded');
3141  
3142 =head3 API SPECIFICATION
3143  
3144 =head4 Input
3145  
3146 { messages => { type => [ 'arrayref', 'scalar' ] } }
3147  
3148 =head4 Output
3149  
3150 { type => 'object', class => 'Log::Abstraction' }
3151  
3152 =head3 MESSAGES
3153  
3154 Croaks if the configured backend is misconfigured, and carps if delivery
3155 fails; see the second table under L</new>'s MESSAGES.
3156  
3157 =cut
3158  
3159 46 ▶sub notice {
Subroutine notice: called CC=1 SCAR=0.0
Pod documented
3160 46 my $self = shift;
3161 46 $self->_log('notice', @_);
3162 45 return $self;
3163 }
3164  
3165 =head2 warn
3166  
3167 $logger->warn(@messages);
3168 $logger->warn(\@messages);
3169 $logger->warn(warning => $text);
3170 $logger->warn({ warning => $text });
3171 $logger->warn(warning => \@parts);
3172 $logger->warn($text, \%fields);
3173  
3174 Logs a warning message. Also dispatches to syslog and/or email backends
3175 when those are configured. Falls back to C<Carp::carp> when no backend
3176 (C<logger>, C<array>, C<file> or C<fd>) is set. The C<Carp::carp> (whether
3177 from C<carp_on_warn> or the fallback) only happens when the message passes
3178 the level threshold.
3179  
3180 Called as a class method (C<Log::Abstraction-E<gt>warn(...)>, or on a
3181 subclass), it calls C<Carp::carp> directly.
3182  
3183 A C<warn()> call with an empty or all-undef argument list is a silent no-op.
3184  
3185 =head3 Arguments
3186  
3187 =over 4
3188  
3189 =item * C<@messages>
3190  
3191 A plain list of strings joined without separator, B<or> a named C<warning>
3192 parameter whose value may be a string or an array reference of strings.
3193 Either form may be followed by a hashref of L</Structured fields>, e.g.
3194 C<warn('Slow query', { ms =E<gt> 1250 })>.
3195  
3196 =back
3197  
3198 =head3 Returns
3199  
3200 C<$self>, to allow method chaining.
3201  
3202 =head3 Side Effects
3203  
3204 Appends to internal message history. Writes to all configured backends.
3205 May call C<Carp::carp> if C<carp_on_warn> is set or no backend is active.
3206  
3207 =head3 Example
3208  
3209 $logger->warn('Disk usage is high');
3210 $logger->warn(warning => 'Connection reset', ' retrying');
3211 $logger->warn({ warning => ['Part A', 'Part B'] });
3212  
3213 =head3 API SPECIFICATION
3214  
3215 =head4 Input
3216  
3217 # Named form
3218 { warning => { type => [ 'scalar', 'arrayref' ] } }
3219 # Plain-list form
3220 { messages => { type => 'arrayref' } }
3221  
3222 =head4 Output
3223  
3224 { type => 'object', class => 'Log::Abstraction' }
3225  
3226 =head3 MESSAGES
3227  
3228 (the warning text itself) Carped if carp_on_warn is set, or if no
3229 backend (logger, array, file or fd) is
3230 configured, provided the warning passes
3231 the level threshold. Also carped when
3232 called as a class method.
3233  
3234 Backend misconfiguration and delivery failures are reported as described
3235 in the second table under L</new>'s MESSAGES.
3236  
3237 =cut
3238  
3239 160 ▶sub warn {
Subroutine warn: called CC=2 SCAR=6.9
Pod documented
3240 160 my $self = shift;
3241  
3242 # Empty argument list is a documented no-op
3243 160 ▶ if(scalar(@_) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ > 0) 156 4 160
3244 156 $self->_high_priority('warn', @_);
3245 }
3246 154 return $self;
3247 }
3248  
3249 =head2 error
3250  
3251 $logger->error(@messages);
3252 $logger->error(warning => $text);
3253 $logger->error($text, \%fields);
3254  
3255 Logs an error-level message. Behaves identically to C<warn()> but at the
3256 C<error> level, which triggers C<Carp::croak> if C<croak_on_error> is set
3257 or no backend (C<logger>, C<array>, C<file> or C<fd>) is set. Called as a
3258 class method, it calls C<Carp::croak> directly.
3259  
3260 =head3 Arguments
3261  
3262 Same argument forms as C<warn()>.
3263  
3264 =head3 Returns
3265  
3266 C<$self>, to allow method chaining. Note: if C<croak_on_error> is set, the
3267 method never returns -- execution unwinds via C<Carp::croak>.
3268  
3269 =head3 Side Effects
3270  
3271 Same as C<warn()> plus optional C<Carp::croak> escalation.
3272  
3273 =head3 Example
3274  
3275 $logger->error('Fatal: database unavailable');
3276  
3277 =head3 API SPECIFICATION
3278  
3279 =head4 Input
3280  
3281 { warning => { type => [ 'scalar', 'arrayref' ], optional => 1 } }
3282  
3283 =head4 Output
3284  
3285 { type => 'object', class => 'Log::Abstraction' }
3286  
3287 =head3 MESSAGES
3288  
3289 Croak Meaning / Action
3290 ---------------------------------------- ------------------------------------------
3291 (the error message text itself) croak_on_error is set, or no backend
3292 (logger, array, file or fd) is
3293 configured, or error() was called as a
3294 class method. The call stack is unwound.
3295 (the error message text itself), as a carp_on_warn is set and croak_on_error
3296 carp is not.
3297  
3298 Backend misconfiguration and delivery failures are reported as described
3299 in the second table under L</new>'s MESSAGES.
3300  
3301 =cut
3302  
3303 235 ▶sub error {
Subroutine error: called CC=1 SCAR=0.0
Pod documented
3304 235 my $self = shift;
3305 235 $self->_high_priority('error', @_);
3306 221 return $self;
3307 }
3308  
3309 =head2 fatal
3310  
3311 $logger->fatal(@messages);
3312  
3313 Synonym for C<error()>. Provided for compatibility with logging frameworks
3314 that use C<fatal> as the highest-severity level name.
3315  
3316 =head3 Arguments
3317  
3318 Same as C<error()>.
3319  
3320 =head3 Returns
3321  
3322 C<$self>.
3323  
3324 =head3 Side Effects
3325  
3326 Same as C<error()>.
3327  
3328 =head3 Example
3329  
3330 $logger->fatal('Unrecoverable state; aborting');
3331  
3332 =head3 API SPECIFICATION
3333  
3334 =head4 Input
3335  
3336 { warning => { type => [ 'scalar', 'arrayref' ], optional => 1 } }
3337  
3338 =head4 Output
3339  
3340 { type => 'object', class => 'Log::Abstraction' }
3341  
3342 =head3 MESSAGES
3343  
3344 Same as C<error()>.
3345  
3346 =cut
3347  
3348 11 ▶sub fatal {
Subroutine fatal: called CC=1 SCAR=0.0
Pod documented
3349 11 my $self = shift;
3350 11 $self->_high_priority('error', @_);
3351 8 return $self;
3352 }
3353  
3354 =head2 Methods above error
3355  
3356 =over 4
3357  
3358 =item critical
3359  
3360 =item alert
3361  
3362 =item emergency
3363  
3364 =back
3365  
3366 $logger->critical(@messages);
3367 $logger->alert(warning => $text);
3368 $logger->emergency($text, \%fields);
3369  
3370 Log a message at a level more severe than C<error>:
3371  
3372 Method Level syslog Priority
3373 ---------- ---------- ------- --------
3374 critical critical crit 2
3375 alert alert alert 1
3376 emergency emergency emerg 0
3377  
3378 =head3 Arguments
3379  
3380 C<critical>, C<alert> and C<emergency> take the same argument forms as
3381 C<warn()>.
3382  
3383 =head3 Returns
3384  
3385 C<$self>, to allow method chaining (unless they croak; see below).
3386  
3387 =head3 Side Effects
3388  
3389 These behave like C<error()>, at a more severe level: C<croak_on_error>, or
3390 having no backend, makes them C<Carp::croak>, and C<carp_on_warn> makes them
3391 C<Carp::carp>. The level string passed to backends is the method name
3392 (C<critical>, C<alert> or C<emergency>, upper-cased in text formats); syslog
3393 gets C<crit>, C<alert> or C<emerg>, and journald C<PRIORITY> 2, 1 or 0. An
3394 object logger without the method (such as L<Log::Log4perl>) is called with
3395 C<fatal>, or C<error> if it has no C<fatal> either.
3396  
3397 =head3 Example
3398  
3399 $logger->critical('Disk 95% full', { mount => '/var' });
3400 $logger->alert('Primary database unreachable');
3401 $logger->emergency('Data corruption detected; shutting down');
3402  
3403 =head3 API SPECIFICATION
3404  
3405 =head4 Input
3406  
3407 { warning => { type => [ 'scalar', 'arrayref' ], optional => 1 } }
3408  
3409 =head4 Output
3410  
3411 { type => 'object', class => 'Log::Abstraction' }
3412  
3413 =head3 MESSAGES
3414  
3415 Same as C<error()>.
3416  
3417 =cut
3418  
3419 30 ▶sub critical {
Subroutine critical: called CC=1 SCAR=0.0
Pod documented
3420 30 my $self = shift;
3421 30 $self->_high_priority('critical', @_);
3422 26 return $self;
3423 }
3424  
3425 27 ▶sub alert {
Subroutine alert: called CC=1 SCAR=0.0
Pod documented
3426 27 my $self = shift;
3427 27 $self->_high_priority('alert', @_);
3428 24 return $self;
3429 }
3430  
3431 28 ▶sub emergency {
Subroutine emergency: called CC=1 SCAR=0.0
Pod documented
3432 28 my $self = shift;
3433 28 $self->_high_priority('emergency', @_);
3434 24 return $self;
3435 }
3436  
3437 # ---------------------------------------------------------------------------
3438 # DESTROY -- release the syslog connection and SIGHUP handler when freed
3439 #
3440 # Purpose: Ensure the syslog socket is closed cleanly on object
3441 # destruction, avoiding resource leaks under persistent
3442 # interpreters such as mod_perl.
3443 # Entry: $self -- the logger object being destroyed.
3444 # Exit: void
3445 # Side effects: Sends any held email digest. Puts back the program's
3446 # SIGHUP handler (_release_sighup) if this was the last
3447 # logger using the module's. Removes the _syslog_opened flag, and calls
3448 # Sys::Syslog::closelog() if no other instance still uses it.
3449 # Notes: Uses fully-qualified Sys::Syslog::closelog() so that
3450 # Test::Mockingbird can intercept the call in tests.
3451 # ---------------------------------------------------------------------------
3452 1776 ▶sub DESTROY {
Subroutine DESTROY: called CC=5 SCAR=16.1
3453 1776 my $self = $_[0];
3454  
3455 # Destructors run at unpredictable times, e.g. while an exception is
3456 # propagating, so don't let closelog() change the error variables
3457 1776 local ($@, $!, $?);
3458  
3459 # Send any messages a sendmail digest is still holding
3460 1776 ▶ eval { $self->flush() } if($self->{_email_digest});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_email_digest"} 1 1775 1776
3461  
3462 # Collect async sendmail children that have finished
3463 1776 ▶ _reap_email_children() if(@email_children);
Branch: 1 branch
BranchTrueFalseTotal
if @email_children 4 1772 1776
3464  
3465 # openlog/closelog are process-global, so only close the connection
3466 # when the last instance using it goes away
3467 1776 ▶ if($self->{_syslog_opened}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_syslog_opened"}) 26 1750 1776
3468 26 delete $self->{_syslog_opened};
3469 26 Log::Abstraction::Backend::Syslog->release_connection();
3470 }
3471  
3472 # Give the program its SIGHUP handler back if no other logger needs ours
3473 1776 ▶ $self->_release_sighup() if($self->{_sighup});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_sighup"} 94 1682 1776
3474 }
3475  
3476 =head1 EXAMPLES
3477  
3478 =head2 CSV file logging for BI import
3479  
3480 The code-reference backend gives you full control over the output format.
3481 The example below writes every message at C<trace> level and above as a
3482 CSV row to a file, producing output that can be loaded directly into a
3483 spreadsheet or BI tool (Tableau, Power BI, Metabase, etc.).
3484  
3485 Each row contains: C<timestamp>, C<level>, C<class>, C<file>, C<line>, C<message>.
3486  
3487 use Log::Abstraction;
3488  
3489 my $csv_file = 'app_events.csv';
3490  
3491 # Write the header row once (skip if the file already exists and has data).
3492 unless (-s $csv_file) {
3493 open my $fh, '>', $csv_file or die "Cannot open $csv_file: $!";
3494 print $fh qq{timestamp,level,class,file,line,message\n};
3495 close $fh;
3496 }
3497  
3498 # Helper: quote a single CSV field (escapes embedded double-quotes).
3499 my $csv_field = sub {
3500 my $v = defined $_[0] ? $_[0] : '';
3501 $v =~ s/"/""/g;
3502 return qq{"$v"};
3503 };
3504  
3505 my $logger = Log::Abstraction->new(
3506 level => 'trace', # capture everything from trace upwards
3507 logger => sub {
3508 my $args = $_[0];
3509  
3510 my $timestamp = POSIX::strftime('%Y-%m-%dT%H:%M:%SZ', gmtime);
3511 my $message = join(' ', @{ $args->{message} // [] });
3512  
3513 open my $fh, '>>', $csv_file or return;
3514 print $fh join(',',
3515 $csv_field->($timestamp),
3516 $csv_field->($args->{level}),
3517 $csv_field->($args->{class}),
3518 $csv_field->($args->{file}),
3519 $csv_field->($args->{line}),
3520 $csv_field->($message),
3521 ), "\n";
3522 close $fh;
3523 },
3524 );
3525  
3526 $logger->trace('application started');
3527 $logger->info('user logged in', { user => 'alice' });
3528 $logger->warn({ warning => 'disk usage above 80%' });
3529  
3530 The resulting C<app_events.csv> looks like:
3531  
3532 timestamp,level,class,file,line,message
3533 "2026-05-27T14:00:00Z","trace","Log::Abstraction","app.pl","42","application started"
3534 "2026-05-27T14:00:01Z","info","Log::Abstraction","app.pl","43","user logged in"
3535 "2026-05-27T14:00:02Z","warn","Log::Abstraction","Log/Abstraction.pm","820","disk usage above 80%"
3536  
3537 Note: C<class> is always C<Log::Abstraction> (or the subclass name if you subclass the
3538 module). For C<trace>, C<debug>, C<info>, and C<notice> calls, C<file> and C<line>
3539 resolve to the caller's source location. For C<warn> and C<error> calls the
3540 extra C<_high_priority> stack frame shifts the resolution one level inward, so
3541 C<file> and C<line> point into the module rather than the calling script.
3542  
3543 For production use, consider replacing the manual C<$csv_field> quoting with
3544 L<Text::CSV> for correct handling of embedded newlines and other edge cases.
3545  
3546 If you also want real-time alerting on critical events, add the email logic
3547 directly inside the code-ref callback -- test C<$args-E<gt>{level}> and call
3548 your mailer for C<warn> / C<error> messages while still writing the CSV row
3549 for every message.
3550  
3551 Alternatively, use the C<sendmail> hash-ref backend on its own (without the
3552 code-ref) and add a C<level> key to restrict emails to warn-and-above:
3553  
3554 my $logger = Log::Abstraction->new(
3555 level => 'warn',
3556 logger => {
3557 sendmail => {
3558 host => 'smtp.example.com',
3559 to => 'ops@example.com',
3560 from => 'logger@example.com',
3561 subject => 'Application alert',
3562 level => 'warn', # only email at warn level and above
3563 min_interval => 300, # at most one alert email per 5 minutes
3564 },
3565 },
3566 );
3567  
3568 Note: the C<sendmail> backend writes the module's standard text format, not
3569 CSV. To produce CSV rows I<and> send email alerts from the same logger,
3570 embed both the CSV-write and the mail-send logic inside a single code-ref
3571 callback as described above.
3572  
3573 =head1 LIMITATIONS
3574  
3575 =over 4
3576  
3577 =item B<trace is the same threshold as debug>
3578  
3579 syslog has no priority below debug, so C<trace> and C<debug> share one
3580 threshold: a logger at C<debug> level also emits C<trace> messages, and
3581 C<trace> can't be filtered separately.
3582  
3583 =item B<Unbounded message history by default>
3584  
3585 Every logged message is kept in the history returned by L</messages>. In a
3586 long-running process (a daemon, or under mod_perl) set C<max_messages> to
3587 stop it growing without bound.
3588  
3589 =item B<syslog connection is shared>
3590  
3591 C<openlog()> and C<closelog()> act on the whole process, so every instance
3592 logging to syslog shares one connection, opened with the C<script_name> of
3593 the first. It is closed when the last such instance is destroyed.
3594  
3595 =item B<Structured fields are text in most backends>
3596  
3597 Only the history, array, CODE-ref, JSON, journald and Log::Any backends
3598 keep L</Structured fields> as data. Text formats, syslog, email,
3599 Log::Dispatch and object loggers get them as C<key=value> text appended to
3600 the message, and a custom C<format> has no token for them on their own.
3601  
3602 =item B<Process-wide state, and no thread safety>
3603  
3604 Some state belongs to the whole process, not to a logger: the syslog
3605 connection (above), the C<$SIG{HUP}> handler (see L</logrotate>), and the
3606 list of C<async> email children still to be reaped. The per-logger state
3607 (open log files, the C<min_interval> throttle and C<digest>, the
3608 first-open syslog flag) is stored on the object without locking. Under
3609 Perl ithreads or other concurrency models, objects shared between threads
3610 are not safe.
3611  
3612 =item B<Asynchronous email uses fork>
3613  
3614 The C<sendmail> C<async> option sends each email from a child made with
3615 C<fork>. That may not suit every program: under mod_perl the child is a
3616 copy of the Apache process; with ithreads only the calling thread is
3617 copied; and in an event loop (L<AnyEvent>, L<IO::Async>, L<Mojo::IOLoop>)
3618 the child is reaped by this module, not by the loop's child watcher. A
3619 program that reaps every child itself (e.g. C<waitpid(-1, ...)> in a
3620 C<$SIG{CHLD}> handler) sees these children too. The child's success or
3621 failure isn't reported back: a failure is carped by the child and the
3622 message is lost. Without C<async> the email is sent in the log call.
3623  
3624 =item B<OpenTelemetry not yet supported>
3625  
3626 The OTel Logs SDK for Perl is incomplete; see the TODO block at the top of
3627 F<lib/Log/Abstraction.pm> for a full status report and the list of blockers.
3628 Monitor L<https://metacpan.org/pod/OpenTelemetry::SDK> for progress.
3629  
3630 =item B<Log::Log4perl is a de-facto required dependency>
3631  
3632 When no C<logger>, C<file>, C<fd> or C<array> backend is configured, C<new()>
3633 loads L<Log::Log4perl> and uses it as the default backend, so it is a
3634 required dependency even for applications that never use it.
3635  
3636 =back
3637  
3638 =head1 AUTHOR
3639  
3640 Nigel Horne C<njh@nigelhorne.com>
3641  
3642 =head1 SEE ALSO
3643  
3644 =over 4
3645  
3646 =item * L<Log::Any> and L<Log::Any::Adapter::Abstraction>
3647  
3648 Route messages from any C<Log::Any>-using CPAN module through
3649 C<Log::Abstraction> with a single C<Log::Any::Adapter-E<gt>set()> call,
3650 or send messages on to Log::Any with the C<log_any> backend.
3651  
3652 =item * L<Log::Abstraction::Backend>
3653  
3654 The classes that send messages to each kind of backend.
3655  
3656 =item * L<Log::Dispatch>
3657  
3658 Send messages on to a C<Log::Dispatch> object with the C<log_dispatch>
3659 backend (see L</Forwarding to Log::Any and Log::Dispatch>).
3660  
3661 =item * L<Test Dashboard|https://nigelhorne.github.io/Log-Abstraction/coverage/>
3662  
3663 =back
3664  
3665 =head1 SUPPORT
3666  
3667 This module is provided as-is without any warranty.
3668  
3669 Please report any bugs or feature requests to C<bug-log-abstraction at rt.cpan.org>,
3670 or through the web interface at
3671 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Log-Abstraction>.
3672 I will be notified, and then you'll
3673 automatically be notified of progress on your bug as I make changes.
3674  
3675 You can find documentation for this module with the perldoc command.
3676  
3677 perldoc Log::Abstraction
3678  
3679 You can also look for information at:
3680  
3681 =over 4
3682  
3683 =item * MetaCPAN
3684  
3685 L<https://metacpan.org/dist/Log-Abstraction>
3686  
3687 =item * RT: CPAN's request tracker
3688  
3689 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Log-Abstraction>
3690  
3691 =item * CPAN Testers' Matrix
3692  
3693 L<http://matrix.cpantesters.org/?dist=Log-Abstraction>
3694  
3695 =item * CPAN Testers Dependencies
3696  
3697 L<http://deps.cpantesters.org/?module=Log::Abstraction>
3698  
3699 =back
3700  
3701 =encoding utf-8
3702  
3703 =head1 FORMAL SPECIFICATION
3704  
3705 =head2 new
3706  
3707 FIELDS == STRING β‡Έ VALUE structured fields (see Structured fields)
3708 ENTRY == { level : STRING; message : STRING; fields : FIELDS }
3709  
3710 entry(l, m, f) == {level ↦ l, message ↦ ρ(m)} βˆͺ (if f = βˆ… then βˆ… else {fields ↦ ρ(f)})
3711  
3712 ρ(x) == if redact = βˆ… then x
3713 else x with each match of redact replaced by '[REDACTED]'
3714 (in strings, recursively in plain hashes and arrays)
3715  
3716 β”Œβ”€ LogState ──────────────────────────────────────────────────
3717 β”‚ level : β„€
3718 β”‚ messages : seq ENTRY
3719 β”‚ max_messages : β„• βˆͺ {∞}
3720 β”‚ logger : LOGGER
3721 β”‚ redact : REGEX βˆͺ {βˆ…}
3722 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3723 β”‚ 0 ≀ level ≀ 7
3724 β”‚ #messages ≀ max_messages
3725 └─────────────────────────────────────────────────────────────
3726  
3727 β”Œβ”€ New ───────────────────────────────────────────────────────
3728 β”‚ args? : Args
3729 β”‚ result! : LogState
3730 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3731 β”‚ result!.level = syslog_values(args?.level ∨ 'warning')
3732 β”‚ result!.messages = ⟨⟩
3733 β”‚ result!.max_messages = args?.max_messages ∨ ∞
3734 β”‚ result!.redact = ⋃ args?.redact {one regex matching any; βˆ… if none}
3735 β”‚ args?.redact β‰  βˆ… ⟹ Β¬('' ∈ L(result!.redact))
3736 β”‚ args?.logger β‰  βˆ… ⟹ result!.logger = args?.logger
3737 β”‚ args?.logger = βˆ… ∧ args?.file = βˆ… ∧ args?.fd = βˆ… ∧ args?.array = βˆ…
3738 β”‚ ⟹ result!.logger = Log4perl
3739 └─────────────────────────────────────────────────────────────
3740  
3741 Clone operation (called on an existing object):
3742  
3743 β”Œβ”€ Clone ─────────────────────────────────────────────────────
3744 β”‚ Ξ”LogState
3745 β”‚ overrides? : Args
3746 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3747 β”‚ result!.level = syslog_values(overrides?.level ∨ level)
3748 β”‚ result!.messages = messages {new sequence; entries shared}
3749 β”‚ result!.logger = overrides?.logger ∨ logger
3750 └─────────────────────────────────────────────────────────────
3751  
3752 =head2 level
3753  
3754 β”Œβ”€ LevelGet ─────────────────────────────────────────────────
3755 β”‚ ΞLogState
3756 β”‚ result! : β„€
3757 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3758 β”‚ result! = level
3759 β”‚ 0 ≀ result! ∧ result! ≀ 7
3760 └─────────────────────────────────────────────────────────────
3761  
3762 β”Œβ”€ LevelSet ─────────────────────────────────────────────────
3763 β”‚ Ξ”LogState
3764 β”‚ new_level? : STRING
3765 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3766 β”‚ new_level? ∈ dom(syslog_values)
3767 β”‚ level' = syslog_values(new_level?)
3768 └─────────────────────────────────────────────────────────────
3769  
3770 β”Œβ”€ LevelSetInvalid ──────────────────────────────────────────
3771 β”‚ ΞLogState
3772 β”‚ new_level? : STRING
3773 β”‚ result! : undef
3774 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3775 β”‚ new_level? β‰  ''
3776 β”‚ new_level? βˆ‰ dom(syslog_values)
3777 β”‚ carp("invalid syslog level")
3778 └─────────────────────────────────────────────────────────────
3779  
3780 level(new_level?) ≑ LevelSet ∨ LevelSetInvalid
3781  
3782 =head2 is_trace, is_debug, is_info, is_notice, is_warn, is_error, is_critical, is_alert, is_emergency
3783  
3784 β”Œβ”€ IsLevel ──────────────────────────────────────────────────
3785 β”‚ ΞLogState
3786 β”‚ lvl? : LEVEL
3787 β”‚ result! : BOOLEAN
3788 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3789 β”‚ result! = (level β‰₯ syslog_values(lvl?))
3790 └─────────────────────────────────────────────────────────────
3791  
3792 is_<lvl> ≑ IsLevel[lvl? := lvl]
3793  
3794 =head2 messages
3795  
3796 β”Œβ”€ Messages ─────────────────────────────────────────────────
3797 β”‚ ΞLogState
3798 β”‚ result! : seq ENTRY
3799 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3800 β”‚ result! = messages
3801 └─────────────────────────────────────────────────────────────
3802  
3803 =head2 flush
3804  
3805 β”Œβ”€ Flush ────────────────────────────────────────────────────
3806 β”‚ Ξ”LogState
3807 β”‚ result! : LogState
3808 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3809 β”‚ digest β‰  ⟨⟩ ∧ (sent(digest) ∨ async ∧ forked) ⟹
3810 β”‚ digest' = ⟨⟩ ∧ last_email_sent' = now
3811 β”‚ digest β‰  ⟨⟩ ∧ Β¬sent(digest) ∧ Β¬(async ∧ forked) ⟹ digest' = digest
3812 β”‚ digest = ⟨⟩ ⟹ digest' = digest
3813 β”‚ messages' = messages
3814 β”‚ result! = self
3815 └─────────────────────────────────────────────────────────────
3816  
3817 =head2 reopen
3818  
3819 INTERVAL == β„€ reopen_interval: seconds, 0 or -1
3820 HANDLE == { fh; dev; ino; sighup : β„•; opened : β„• }
3821  
3822 β”Œβ”€ OpenFiles ─────────────────────────────────────────────────
3823 β”‚ handles : PATH β‡Έ HANDLE
3824 β”‚ reopen_interval : INTERVAL
3825 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3826 β”‚ reopen_interval β‰₯ -1
3827 β”‚ reopen_interval = 0 ⟹ handles = βˆ… (between log calls)
3828 └─────────────────────────────────────────────────────────────
3829  
3830 A handle h on path p is used for the next write iff
3831 stat(p) = (h.dev, h.ino) ∧ h.sighup = sighup_count
3832 ∧ (reopen_interval = -1 ∨ now - h.opened < reopen_interval)
3833 and is otherwise closed and p opened again.
3834  
3835 β”Œβ”€ Reopen ────────────────────────────────────────────────────
3836 β”‚ Ξ”OpenFiles
3837 β”‚ result! : LogState
3838 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3839 β”‚ handles' = βˆ…
3840 β”‚ reopen_interval' = reopen_interval
3841 β”‚ result! = self
3842 └─────────────────────────────────────────────────────────────
3843  
3844 =head2 trace
3845  
3846 β”Œβ”€ Trace ────────────────────────────────────────────────────
3847 β”‚ Ξ”LogState
3848 β”‚ msg? : seq STRING
3849 β”‚ fields? : FIELDS
3850 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3851 β”‚ syslog_values('trace') ≀ level
3852 β”‚ messages' = messages ⌒ ⟨entry('trace', βŠ•(msg?), fields?)⟩
3853 └─────────────────────────────────────────────────────────────
3854  
3855 =head2 debug
3856  
3857 β”Œβ”€ Debug ────────────────────────────────────────────────────
3858 β”‚ Ξ”LogState
3859 β”‚ msg? : seq STRING
3860 β”‚ fields? : FIELDS
3861 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3862 β”‚ syslog_values('debug') ≀ level
3863 β”‚ messages' = messages ⌒ ⟨entry('debug', βŠ•(msg?), fields?)⟩
3864 └─────────────────────────────────────────────────────────────
3865  
3866 =head2 info
3867  
3868 β”Œβ”€ Info ─────────────────────────────────────────────────────
3869 β”‚ Ξ”LogState
3870 β”‚ msg? : seq STRING
3871 β”‚ fields? : FIELDS
3872 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3873 β”‚ syslog_values('info') ≀ level
3874 β”‚ messages' = messages ⌒ ⟨entry('info', βŠ•(msg?), fields?)⟩
3875 └─────────────────────────────────────────────────────────────
3876  
3877 =head2 notice
3878  
3879 β”Œβ”€ Notice ───────────────────────────────────────────────────
3880 β”‚ Ξ”LogState
3881 β”‚ msg? : seq STRING
3882 β”‚ fields? : FIELDS
3883 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3884 β”‚ syslog_values('notice') ≀ level
3885 β”‚ messages' = messages ⌒ ⟨entry('notice', βŠ•(msg?), fields?)⟩
3886 └─────────────────────────────────────────────────────────────
3887  
3888 =head2 warn
3889  
3890 β”Œβ”€ Warn ─────────────────────────────────────────────────────
3891 β”‚ Ξ”LogState
3892 β”‚ msg? : seq STRING | { warning : STRING | seq STRING }
3893 β”‚ fields? : FIELDS
3894 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3895 β”‚ msg? β‰  βˆ… ∧ join(msg?) β‰  ''
3896 β”‚ syslog_values('warn') ≀ level
3897 β”‚ messages' = messages ⌒ ⟨entry('warn', join(msg?), fields?)⟩
3898 β”‚ (carp_on_warn ∨ no_backend) ⟹ carp(join(msg?))
3899 └─────────────────────────────────────────────────────────────
3900  
3901 no_backend ≑ logger = βˆ… ∧ array = βˆ… ∧ file = βˆ… ∧ fd = βˆ…
3902  
3903 Called as a class method (no LogState): carp(join(msg?)), and
3904 messages is not touched.
3905  
3906 =head2 error
3907  
3908 β”Œβ”€ Error ────────────────────────────────────────────────────
3909 β”‚ Ξ”LogState
3910 β”‚ msg? : seq STRING | { warning : STRING | seq STRING }
3911 β”‚ fields? : FIELDS
3912 β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
3913 β”‚ msg? β‰  βˆ… ∧ join(msg?) β‰  ''
3914 β”‚ syslog_values('error') ≀ level
3915 β”‚ messages' = messages ⌒ ⟨entry('error', join(msg?), fields?)⟩
3916 β”‚ (croak_on_error ∨ no_backend) ⟹ execution_continues = false
3917 └─────────────────────────────────────────────────────────────
3918  
3919 Called as a class method (no LogState): croak(join(msg?)).
3920  
3921 =head2 fatal
3922  
3923 fatal ≑ error (identical operation schema)
3924  
3925 =head2 critical, alert, emergency
3926  
3927 The Error schema, with 'error' replaced by 'critical', 'alert' or
3928 'emergency' respectively.
3929  
3930 In every logging schema, when #messages' would exceed max_messages
3931 the oldest entries are dropped: messages' = the last max_messages
3932 entries. fields? is a hashref given after the message (see
3933 Structured fields); fields? = βˆ… when there is none.
3934  
3935 =head1 COPYRIGHT AND LICENSE
3936  
3937 Copyright (C) 2025-2026 Nigel Horne
3938  
3939 Usage is subject to the GPL2 licence terms.
3940 If you use it,
3941 please let me know.
3942  
3943 =cut
3944  
3945 42 1;
↑ Summary blib/lib/Log/Abstraction/Backend/Journald.pm »