Using Log4perl Singleton

I am new to Log4perl and trying to understand why in the setup below I get two different loggers. I understand that this must be a singleton, and calling get_logger () will return the same instance of the object each time.

Test.pm

#!/usr/bin/perl

package Example::Test;
use strict;
use warnings;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(test);

sub test 
{
    my $logger = Log::Log4perl->get_logger();
    print $logger, "\n";
}

test.pl

#!/usr/bin/perl

use strict;
use warnings;
use Log::Log4perl;
use Example::Test;

# Logger configuration
Log::Log4perl->init('/etc/log4perl.conf');
my $logger = Log::Log4perl->get_logger();
print $logger, "\n";

my $engine = test();

Output

Log::Log4perl::Logger=HASH(0x12093d0)
Log::Log4perl::Logger=HASH(0x29b4950)
+4
source share
1 answer

You did not specify a registration category, so your code executes the equivalent

Log::Log4perl->get_logger(__PACKAGE__);

where __PACKAGE__is Example::Testinside your module and maininside your script.

From the documentation :

"Loggers" Log4perl, , . Log::Log4perl , . - , ...

, , , , -.


, Example::Test Log:: Log4perl, :

package My::Wrapper;

use strict;
use warnings 'all';
use 5.010;

use Log::Log4perl;

Log::Log4perl->wrapper_register(__PACKAGE__);

sub foo {
    my $logger = Log::Log4perl->get_logger;

    say $logger;
    $logger->warn('foo');
}

1;

My::Wrapper::foo() main, main::.

+3
source

Source: https://habr.com/ru/post/1659754/


All Articles