blib/lib/Log/Abstraction/Backend/Journald.pm

filter: Statementstmt 100% 110 / 110 Branchbran 90.0% 18 / 20 Conditioncond 78.2% 18 / 23 MC/DCmcdc 42.8% 6 / 14 Subroutinesub 100% 16 / 16 Podpod 100% 2 / 2 totaltotal 91.8% 170 / 185 CC 22 SCAR 16.1
CC
22
Cov
95%
emit
9.0
_send
8.0
__ANON__
4.0
CRAP 5.0
« blib/lib/Log/Abstraction.pm ↑ Summary blib/lib/Log/Abstraction/Backend/Object.pm »
1 package Log::Abstraction::Backend::Journald;
2  
3 # The journald backend: send messages to the systemd journal
4 42 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 42 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 42 ▶use parent 'Log::Abstraction::Backend';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Automatically throw exceptions on failed built-ins (socket, close ...)
10 42 ▶use autodie qw(:default);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 42 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 42 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 42 ▶use Readonly ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 # _send is private to this package (see Log::Abstraction)
17 42 ▶use Sub::Private 0.07 { mode => 'enforce' };
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 42 our $VERSION = '0.40';
20  
21 # Default path to the journald native-protocol socket on systemd systems
22 42 Readonly::Scalar my $DEFAULT_SOCKET => '/run/systemd/journal/socket';
23  
24 # Largest journald datagram sent; the default socket send buffer is ~212KB
25 # on most Linux systems and bigger datagrams fail, so longer messages are
26 # truncated to fit. Some systems have smaller buffers, so on EMSGSIZE the
27 # limit is halved and the send retried, down to $MIN_PAYLOAD
28 42 Readonly::Scalar my $MAX_PAYLOAD => 200_000;
29 42 Readonly::Scalar my $MIN_PAYLOAD => 4_096;
30  
31 # Longest journald field name; journald ignores fields with longer names
32 42 Readonly::Scalar my $MAX_FIELD_NAME => 64;
33  
34 # Marker appended to a message truncated to fit in a datagram
35 42 Readonly::Scalar my $TRUNCATED_MARKER => ' [truncated]';
36  
37 =head1 NAME
38  
39 Log::Abstraction::Backend::Journald - send messages to the systemd journal
40  
41 =head1 VERSION
42  
43 0.40
44  
45 =head1 DESCRIPTION
46  
47 Built for the C<journald> key of a C<logger> hash. Each message is one
48 datagram in the journald native protocol
49 (L<https://systemd.io/JOURNAL_NATIVE_PROTOCOL/>), with the fields
50 C<MESSAGE> (with a C<format>, the formatted line), C<PRIORITY>,
51 C<SYSLOG_IDENTIFIER>, the hash's other keys upper-cased, and the structured
52 fields. A message too big for one datagram is truncated. A failed send
53 carps, once until a send succeeds again. The socket is opened for the
54 first message and reused for the next ones, until a send fails.
55  
56 For use by L<Log::Abstraction> only; see L<Log::Abstraction::Backend>.
57  
58 =head1 METHODS
59  
60 =head2 new
61  
62 my $backend = Log::Abstraction::Backend::Journald->new(
63 journald => \%journald, level => $level, format => $format,
64 );
65  
66 =cut
67  
68 24 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
69 24 my ($class, %args) = @_;
70  
71 # The config hash's other keys are extra journal fields (their names
72 # have been checked by Log::Abstraction->new())
73 24 my $config = $args{'journald'};
74 5 my %extra = map { uc($_) => $config->{$_} }
75 24 grep { lc($_) !~ /^(?:socket|identifier|level|format)$/ } keys %{$config};
76  
77 return $class->SUPER::new(
78 %args,
79 socket => $config->{'socket'} || $DEFAULT_SOCKET,
80 24 ▶ identifier => $config->{'identifier'},
Condition66%2/3
$config->{'socket'} || $DEFAULT_SOCKET
l!l&&r!l&&!r
2310
MC/DC0%0/2
$config->{'socket'} || $DEFAULT_SOCKET
$config->{'socket'} $DEFAULT_SOCKET
Truth table66%2/3
A || B
A= $config->{'socket'}B= $DEFAULT_SOCKET
ABresult
1X1
011
000
81 extra => \%extra,
82 );
83 }
84  
85 =head2 emit
86  
87 $backend->emit($logger, $event);
88  
89 =cut
90  
91 40 ▶sub emit {
Subroutine emit: called CC=9 SCAR=22.0
Pod documented
92 40 my ($self, $logger, $event) = @_;
93  
94 # The syslog identifier: the configured one, the script name, or $0
95 40 ▶ my $ident = $self->{'identifier'} || $logger->{'script_name'} || do {
Condition66%4/6
$self->{'identifier'} || $logger->{'script_name'} || do { require File::Basename; File::Basename::basename($0) }
l!l&&r!l&&!r
3370
$self->{"identifier"} or $logger->{"script_name"}
l!l&&r!l&&!r
3037
MC/DC0%0/3
$self->{'identifier'} || $logger->{'script_name'} || do { require File::Basename; File::Basename::basename($0) }
$self->{"identifier"} $logger->{"script_name"} do { require File::Basename; File::Basename::basename($0) }
Truth table50%2/4
A or B || C
A= $self->{"identifier"}B= $logger->{"script_name"}C= do { require File::Basename; File::Basename::basename($0) }
ABCresult
1XX1
01X1
0011
0000
96 37 require File::Basename;
97 37 File::Basename::basename($0);
98 };
99  
100 # Mandatory fields (PRIORITY is 0=emerg ... 7=debug), then the extra
101 # fields from the config hash
102 my %entry = (
103 MESSAGE => $self->text($event, $event->{'message'}),
104 PRIORITY => $event->{'priority'},
105 SYSLOG_IDENTIFIER => $ident,
106 40 %{$self->{'extra'}},
107 );
108  
109 # Then the structured fields. These weren't checked by new(), so make
110 # each name valid rather than reject it: upper-case, other characters
111 # to '_', no leading '_' (journald reserves those for trusted fields)
112 # and at most 64 characters
113 40 ▶ my $fields = $event->{'fields'} || {};
Condition100%2/2
$event->{'fields'} || {}
l!l
1228
MC/DC100%1/1
$event->{'fields'} || {}
$event->{'fields'}
Truth table100%2/2
A
A= $event->{'fields'}
Aresult
11
00
114 40 for my $key (keys %{$fields}) {
115 20 (my $name = uc($key)) =~ s/[^A-Z0-9_]/_/g;
116 20 $name =~ s/^_+//;
117 20 $name = substr($name, 0, $MAX_FIELD_NAME);
118 20 ▶ next if(($name eq '') || $name =~ /^(?:MESSAGE|PRIORITY|SYSLOG_IDENTIFIER)$/);
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "" or $name =~ /^(?:MESSAGE|PRIORITY|SYSLOG_IDENTIFIER)$/ 4 16 20
Condition100%3/3
$name eq "" or $name =~ /^(?:MESSAGE|PRIORITY|SYSLOG_IDENTIFIER)$/
l!l&&r!l&&!r
1316
MC/DC100%2/2
$name eq "" or $name =~ /^(?:MESSAGE|PRIORITY|SYSLOG_IDENTIFIER)$/
$name eq "" $name =~ /^(?:MESSAGE|PRIORITY|SYSLOG_IDENTIFIER)$/
Truth table100%3/3
A or B
A= $name eq ""B= $name =~ /^(?:MESSAGE|PRIORITY|SYSLOG_IDENTIFIER)$/
ABresult
1X1
011
000
119 16 $entry{$name} = $event->{'field_string'}->($fields->{$key});
120 }
121  
122 # Delivery failures are silent; the app must not crash on log errors.
123 # Carp only on the first failure, so that a system without journald
124 # (FreeBSD, macOS) isn't flooded with warnings; a later success re-arms
125 # the warning.
126 40 ▶ if(eval { $self->_send($self->{'socket'}, %entry); 1 }) {
Branch: 2 branches
BranchTrueFalseTotal
if (eval { do { $self->_send($self->{'socket'}, %entry); 1 } }) { } 20 20 40
elsif (not $logger->{'_journald_failed'}++) { } 6 14 20
127 20 delete $logger->{'_journald_failed'};
128 } elsif(!$logger->{'_journald_failed'}++) {
129 6 Carp::carp(ref($logger), ": journald send failed: $@");
130 }
131 }
132  
133 # ---------------------------------------------------------------------------
134 # _send -- encode fields and send one datagram to the journald socket
135 #
136 # Purpose: Format key=value fields in the journald native protocol and
137 # deliver them as a single Unix-domain SOCK_DGRAM packet.
138 # Entry: $self -- the backend, which keeps the socket in
139 # $self->{_socket} between messages.
140 # $socket_path -- filesystem path of the journald socket.
141 # %fields -- FIELD_NAME => value pairs; names must be
142 # uppercase ASCII + digits + underscore.
143 # Exit: Returns nothing. Croaks on socket or send failure (the caller
144 # wraps every call in eval{} so failures are silent to the app).
145 # Side effects: Opens a Unix datagram socket on the first call, and keeps it
146 # for the next; closes it after a failed send, so that the
147 # next message gets a new one.
148 # Notes: Values containing newline or NUL use the binary framing
149 # (field-name NL uint64-LE-length value NL) as specified by
150 # https://systemd.io/JOURNAL_NATIVE_PROTOCOL/.
151 # Values without newlines or NULs use the simpler FIELD=VALUE NL
152 # text format. The send buffer, and so the largest datagram,
153 # varies between systems: a send failing with EMSGSIZE is
154 # retried with MESSAGE truncated to half the size, down to
155 # $MIN_PAYLOAD. The socket isn't connected: each datagram is
156 # addressed to the path, so it still arrives after journald
157 # restarts and creates the socket file again.
158 # ---------------------------------------------------------------------------
159 32 ▶sub _send :Private {
Subroutine _send: called CC=8 SCAR=20.8
160 32 my ($self, $socket_path, %fields) = @_;
161  
162 # The protocol carries bytes, and binary framing declares a byte length,
163 # so encode character strings to UTF-8 first
164 32 for my $key (keys %fields) {
165 102 ▶ my $value = defined($fields{$key}) ? "$fields{$key}" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $fields{$key} ? : 102 0 102
166 102 ▶ utf8::encode($value) if(utf8::is_utf8($value));
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($value) 1 101 102
167 102 $fields{$key} = $value;
168 }
169  
170 # Build the datagram payload from all supplied fields
171 43 ▶ my $build = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
172 43 my $payload = '';
173 43 for my $key (sort keys %fields) {
174 135 my $value = $fields{$key};
175 135 ▶ if($value =~ /[\n\0]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /[\n\0]/) { } 8 127 135
176 # Binary framing: field-name LF uint64LE-length value LF.
177 # The length is packed as two 32-bit little-endian words
178 # because pack('Q') dies on perls without 64-bit integers
179 8 my $len = length($value);
180 8 $payload .= $key . "\n"
181 . pack('VV', $len % 2**32, int($len / 2**32))
182 . $value . "\n";
183 } else {
184 127 $payload .= "$key=$value\n";
185 }
186 }
187 43 return $payload;
188 32 };
189 32 my $full = $build->();
190 32 my $message = $fields{'MESSAGE'};
191  
192 # A datagram bigger than the socket send buffer fails outright, so
193 # truncate MESSAGE to fit in $limit bytes. The extra 8 bytes allow for
194 # the message switching from text to binary framing.
195 40 ▶ my $fit = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
196 40 my $limit = shift;
197 40 my $excess = length($full) - $limit;
198 40 ▶ return $full if(($excess <= 0) || !defined($message));
Branch: 1 branch
BranchTrueFalseTotal
if $excess <= 0 or not defined $message 29 11 40
Condition66%2/3
$excess <= 0 or not defined $message
l!l&&r!l&&!r
29011
MC/DC50%1/2
$excess <= 0 or not defined $message
$excess <= 0 not defined $message
Truth table66%2/3
A or not(B)
A= $excess <= 0B= not defined $message
ABresult
1X1
011
000
199 11 my $keep = length($message) - $excess - length($TRUNCATED_MARKER) - 8;
200 11 ▶ my $cut = substr($message, 0, ($keep > 0) ? $keep : 0);
Branch: 1 branch
BranchTrueFalseTotal
$keep > 0 ? : 11 0 11
201 # Don't leave a partial UTF-8 sequence at the cut
202 11 $cut =~ s/[\xC0-\xFF][\x80-\xBF]*\z//;
203 11 $fields{'MESSAGE'} = $cut . $TRUNCATED_MARKER;
204 11 return $build->();
205 32 };
206  
207 # The Unix-domain datagram socket, opened on the first message and then
208 # reused
209 32 require Socket;
210 32 ▶ my $sock = $self->{_socket} //= do {
Condition66%2/3
$self->{"_socket"} //= do { socket my $new, &Socket::AF_UNIX(), &Socket::SOCK_DGRAM(), 0; BEGIN { $^H{'autodie::Scope::GuardStack/guard3'} = 'autodie::Scope::Guard=CODE(0x5b7552d842c0)'; $^H{'no Fatal'} = 'HASH(0x5b7552d84260)'; } setsockopt $new, &Socket::SOL_SOCKET(), &Socket::SO_SNDBUF(), $MAX_PAYLOAD + 1024; $new }
l!l&&r!l&&!r
3290
MC/DC0%0/2
$self->{"_socket"} //= do { socket my $new, &Socket::AF_UNIX(), &Socket::SOCK_DGRAM(), 0; BEGIN { $^H{'autodie::Scope::GuardStack/guard3'} = 'autodie::Scope::Guard=CODE(0x5b7552d842c0)'; $^H{'no Fatal'} = 'HASH(0x5b7552d84260)'; } setsockopt $new, &Socket::SOL_SOCKET(), &Socket::SO_SNDBUF(), $MAX_PAYLOAD + 1024; $new }
$self->{"_socket"} do { socket my $new, &Socket::AF_UNIX(), &Socket::SOCK_DGRAM(), 0; BEGIN { $^H{'autodie::Scope::GuardStack/guard3'} = 'autodie::Scope::Guard=CODE(0x5b7552d842c0)'; $^H{'no Fatal'} = 'HASH(0x5b7552d84260)'; } setsockopt $new, &Socket::SOL_SOCKET(), &Socket::SO_SNDBUF(), $MAX_PAYLOAD + 1024; $new }
Truth table66%2/3
A //= B
A= $self->{"_socket"}B= do { socket my $new, &Socket::AF_UNIX(), &Socket::SOCK_DGRAM(), 0; BEGIN { $^H{'autodie::Scope::GuardStack/guard3'} = 'autodie::Scope::Guard=CODE(0x5b7552d842c0)'; $^H{'no Fatal'} = 'HASH(0x5b7552d84260)'; } setsockopt $new, &Socket::SOL_SOCKET(), &Socket::SO_SNDBUF(), $MAX_PAYLOAD + 1024; $new }
ABresult
1X1
011
000
211 29 socket(my $new, Socket::AF_UNIX(), Socket::SOCK_DGRAM(), 0);
212  
213 # Ask for a send buffer big enough for the largest datagram; the
214 # kernel may cap it (net.core.wmem_max), which the retry handles
215 42 ▶ no autodie qw(setsockopt);
Subroutine BEGIN: called CC=1 SCAR=0.0
216 29 setsockopt($new, Socket::SOL_SOCKET(), Socket::SO_SNDBUF(), $MAX_PAYLOAD + 1024);
217 29 $new;
218 };
219 32 my $dest = Socket::sockaddr_un($socket_path);
220  
221 {
222 # send() is checked by hand: EMSGSIZE means retry smaller
223 42 ▶ no autodie qw(send);
Subroutine BEGIN: called CC=1 SCAR=0.0
224  
225 32 my $limit = $MAX_PAYLOAD;
226 32 while(1) {
227 40 ▶ last if(defined(send($sock, $fit->($limit), 0, $dest)));
Branch: 1 branch
BranchTrueFalseTotal
if defined send($sock, &$fit($limit), 0, $dest) 20 20 40
228 20 my $err = $!;
229 20 ▶ if(($err == POSIX::EMSGSIZE()) && ($limit > $MIN_PAYLOAD)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err == 90 and $limit > $MIN_PAYLOAD) 8 12 20
Condition100%3/3
$err == 90 and $limit > $MIN_PAYLOAD
!ll&&!rl&&r
1118
MC/DC100%2/2
$err == 90 and $limit > $MIN_PAYLOAD
$err == 90 $limit > $MIN_PAYLOAD
Truth table100%3/3
A and B
A= $err == 90B= $limit > $MIN_PAYLOAD
ABresult
0X0
100
111
230 8 $limit = int($limit / 2);
231 8 next;
232 }
233 # Start again with a new socket next time
234 12 delete $self->{_socket};
235 12 eval { close $sock };
236 12 Carp::croak("Can't send to $socket_path: $err");
237 }
238 }
239 20 return;
240 42 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
241  
242  
243 =head1 AUTHOR
244  
245 Nigel Horne C<njh@nigelhorne.com>
246  
247 =head1 SEE ALSO
248  
249 L<Log::Abstraction>, L<Log::Abstraction::Backend>
250  
251 =head1 COPYRIGHT AND LICENSE
252  
253 Copyright (C) 2025-2026 Nigel Horne
254  
255 Usage is subject to the GPL2 licence terms.
256 If you use it,
257 please let me know.
258  
259 =cut
260  
261 42 1;
« blib/lib/Log/Abstraction.pm ↑ Summary blib/lib/Log/Abstraction/Backend/Object.pm »