加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Log4perl Singleton用法

发布时间:2020-12-16 06:16:10 所属栏目:大数据 来源:网络整理
导读:我是Log4perl的新手,我想弄清楚为什么我在下面的设置中得到两个不同的记录器.我的理解是,这应该是一个单例,并且调用get_logger()每次都会返回相同的对象实例. Test.pm #!/usr/bin/perlpackage Example::Test;use strict;use warnings;use Exporter;our @ISA
我是Log4perl的新手,我想弄清楚为什么我在下面的设置中得到两个不同的记录器.我的理解是,这应该是一个单例,并且调用get_logger()每次都会返回相同的对象实例.

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__是示例::在模块内部进行测试,在主要内部进行测试.

从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 ::.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读