gpt4 book ai didi

perl - Log4perl:如何在运行时动态加载附加程序?

转载 作者:行者123 更新时间:2023-12-04 07:11:23 25 4
gpt4 key购买 nike

我想让模块在运行时管理它们的日志记录,但不要让所有东西都引用一个单一的整体配置文件。在处理在不同权限下运行的进程时,我真的不想处理需要能够访问系统上每个日志的每个进程,而它们只写入其中的一个子集。

但是,我在 Log4perl 手册中没有找到太多关于如何在运行时从配置文件初始化附加附加程序的文档。 http://metacpan.org/pod/Log::Log4perl::Appender引用 add_appender 方法,但它适用于实例化的 appender 对象而不是 conf 文件。它也没有定义 logger 对象和 logger->appender 关系。

我尝试让每个包从它自己的 conf 中初始化,但这只会在每次初始化时破坏现有配置。我想做的是类似的事情:

my $foo = Foo->new() ## Checks Log::Log4perl::initialized(), sees that it
## hasn't been initalized yet, inits Log4perl from foo.conf
my $bar = Bar->new() ## Checks Log::Log4perl::initialized(), sees that it
## has been initalized. Adds appenders and loggers defined
## in bar.conf into the initialized configuration

如何解析配置并将其添加到当前配置中?

编辑:使用包变量的问题在于,这只是一个被各种类使用的 Moose 角色,几乎只是 Ether 在 Making self-logging modules with Log::Log4perl 中的答案的 MooseX::Role::Parameterized 版本.因此,我的记录器正在组合到使用它的库中,并且我没有每次使用它时都可以处理的全局变量。

尽管..

如果我在 MooseX::Role::Parameterized 角色 block 之外声明一个全局变量,是否每个使用该角色的类都使用相同的 conf 变量?

最佳答案

你可以记住已经加载了哪些配置文件(下面代码中的 %log_configs 哈希)。当新类(class)到来时,您可以重新阅读所有配置,将它们合并在一起并初始化Log::Log4perl再次使用 init 的字符串引用参数.

我通常更喜欢每个应用程序有一个日志配置,因为更容易维护和重新加载功能。

package Logger;
use Moose::Role;
use Log::Log4perl;

our %log_configs = ();

around BUILDARGS => sub {
my $orig = shift;
my $class = shift;

my $config_name = lc($class) . '.conf';

# if the config is not integrated yet
if(! defined $log_configs{$config_name}) {
$log_configs{$config_name} = 1;

# reload all configs including new one
my $config_text = '';
for my $file (sort keys %log_configs) {
$config_text .= "\n" . do {
local $/; # slurp
unless(open my $fh, "<", $file) {
warn "$file could not be open\n";
'';
}
else {
<$fh>
}
};
}

# refresh config
Log::Log4perl::init(\$config_text);
}

return $class->$orig(@_);
};


package Foo;
use Moose;
with 'Logger';
use Log::Log4perl ':easy';

sub BUILD {
ERROR 'Foo reporting';
}


package Bar;
use Moose;
with 'Logger';
use Log::Log4perl ':easy';

sub BUILD {
INFO 'Bar reporting';
}


package main;

my $foo = Foo->new;
my $bar = Bar->new;

关于perl - Log4perl:如何在运行时动态加载附加程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4715909/

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