log4perl 如何同时写入 STDERR 和文件?
我尝试设置两个附加程序,但它似乎只写入 STDERR:
my $header = "######$scriptname $version";
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init($DEBUG);
my $logger = get_logger();
my $layout = Log::Log4perl::Layout::PatternLayout->new(
"%d %p> %F{1}:%L %M - %m%n");
my $appender = Log::Log4perl::Appender->new(
"Log::Dispatch::File",
filename=>$scriptname.".log",
mode => "append"
);
$appender->layout($layout);
my $stderr = Log::Log4perl::Appender::Screen->new(
stderr =>0,
);
$stderr->layout($layout);
$logger->info($header);
I tried to set up two appenders, but it seems to only write to STDERR:
my $header = "######$scriptname $version";
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init($DEBUG);
my $logger = get_logger();
my $layout = Log::Log4perl::Layout::PatternLayout->new(
"%d %p> %F{1}:%L %M - %m%n");
my $appender = Log::Log4perl::Appender->new(
"Log::Dispatch::File",
filename=>$scriptname.".log",
mode => "append"
);
$appender->layout($layout);
my $stderr = Log::Log4perl::Appender::Screen->new(
stderr =>0,
);
$stderr->layout($layout);
$logger->info($header);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
easy_init
与自定义附加程序混合使用并不是一个好主意。您可以通过向记录器添加附加程序$logger->add_appender($appender)
来解决此问题。但这会导致重复的消息,因为您已经在easy_init
中设置了appender。我建议您改用配置。您可以在代码中嵌入配置:
It's not a good idea to mix
easy_init
with custom appenders. You can fix this by adding appender to logger$logger->add_appender($appender)
. But this will result in duplicated messages, because you've already set appender ineasy_init
.I suggest you to use configuration instead. You can embed configuration in you code:
Log::Log4Perl 文档在“Stealth Logger”部分中给出了答案:
http://search.cpan.org /~mschilli/Log-Log4perl-1.49/lib/Log/Log4perl.pm#Stealth_loggers
我也有同样的问题......即使是 5 年后这个已经发布了,当搜索“perl log4perl write to file and screen”时,它仍然出现在 Google 的首页上
The Log::Log4Perl documentation has the answer half-way through the 'Stealth Logger' section:
http://search.cpan.org/~mschilli/Log-Log4perl-1.49/lib/Log/Log4perl.pm#Stealth_loggers
I had the same question... even 5 years after this was posted, this is still on the front page of Google when searching "perl log4perl write to file and screen"