Log4perl 单例使用

Log4perl Singleton usage

我是 Log4perl 的新手,我想弄清楚为什么我在下面的设置中得到两个不同的记录器。我的理解是,这应该是一个单例,并且每次调用 get_logger() 都会 return 相同的对象实例。

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();

输出

Log::Log4perl::Logger=HASH(0x12093d0)
Log::Log4perl::Logger=HASH(0x29b4950)

您没有指定日志类别,因此您的代码相当于

Log::Log4perl->get_logger(__PACKAGE__);

其中 __PACKAGE__ 在您的模块中 Example::Test 而在您的脚本中 main

来自documentation:

Categories are also called "Loggers" in Log4perl, both refer to the same thing and these terms are used interchangeably. Log::Log4perl uses categories to determine if a log statement in a component should be executed or suppressed at the current logging level. Most of the time, these categories are just the classes the log statements are located in...

通常,您可能希望每个模块都有一个单独的记录器,以便您可以不同地处理来自代码库不同部分的日志消息。


另一方面,如果 Example::Test 应该是 Log::Log4perl 的包装器,register it:

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;

当您从包 main 调用 My::Wrapper::foo() 时,日志记录类别将为 main::