File Coverage

File:blib/lib/Log/Abstraction/Backend/Object.pm
Coverage:97.6%

linestmtbrancondsubtimecode
1package Log::Abstraction::Backend::Object;
2
3# The object backend: call the logger object's method for the level
4
37
37
37
98
20
149
use strict;
5
37
37
37
31
18
317
use warnings;
6
7
37
37
37
32
20
43
use parent 'Log::Abstraction::Backend';
8
9
37
37
37
384
23
2970
use Carp ();
10
11our $VERSION = '0.40';
12
13 - 39
=head1 NAME

Log::Abstraction::Backend::Object - call a logger object's method for each message

=head1 VERSION

0.40

=head1 DESCRIPTION

Built for any object given as the C<logger> other than a L<Log::Any> logger
or a L<Log::Dispatch> object (see L<Log::Abstraction::Backend::LogAny> and
L<Log::Abstraction::Backend::LogDispatch>), e.g. a L<Log::Log4perl> logger.
The method named after the level is called with the message's parts, and
the structured fields as C<key=value> text.  An object without a
C<notice> method gets C<info>; one without C<critical>, C<alert> or
C<emergency> gets C<fatal>, or else C<error>.  Otherwise it croaks.

For use by L<Log::Abstraction> only; see L<Log::Abstraction::Backend>.

=head1 METHODS

=head2 emit

  $backend->emit($logger, $event);

=cut
40
41sub emit {
42
23
22
        my ($self, $logger, $event) = @_;
43
44
23
23
        my $object = $self->{'object'};
45
23
15
        my $method = $event->{'level'};
46
23
49
        if(!$object->can($method)) {
47                # Log::Log4perl has no notice(), critical(), alert() or
48                # emergency(); use the nearest method it does have
49
9
17
                my @fallbacks = ($method eq 'notice') ? ('info')
50                        : ($method =~ /^(?:critical|alert|emergency)$/) ? ('fatal', 'error')
51                        : ();
52
9
13
8
16
                ($method) = grep { $object->can($_) } @fallbacks;
53
9
13
                if(!defined($method)) {
54
3
25
                        Carp::croak(
55                                ref($logger), ': ', ref($object),
56                                " doesn't know how to deal with the $event->{level} message",
57                        );
58                }
59        }
60
20
15
        my $fields_text = $event->{'fields_text'};
61        $object->$method(
62
20
39
                @{$event->{'parts'}},
63
20
16
                (defined($fields_text) ? ((length($event->{'message'}) ? ' ' : '') . $fields_text) : ()),
64        );
65}
66
67 - 83
=head1 AUTHOR

Nigel Horne C<njh@nigelhorne.com>

=head1 SEE ALSO

L<Log::Abstraction>, L<Log::Abstraction::Backend>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2025-2026 Nigel Horne

Usage is subject to the GPL2 licence terms.
If you use it,
please let me know.

=cut
84
851;