gpt4 book ai didi

perl - Log4perl 单例使用

转载 作者:行者123 更新时间:2023-12-01 01:56:05 25 4
gpt4 key购买 nike

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

测试.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;

当您调用 My::Wrapper::foo()来自包装 main ,日志记录类别将为 main:: .

关于perl - Log4perl 单例使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40407990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com