本文介绍了log4perl 如何同时写入 STDERR 和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试设置两个 appender,但它似乎只写入 STDERR:
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);
推荐答案
将 easy_init
与自定义 appender 混合使用并不是一个好主意.您可以通过将 appender 添加到记录器 $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 in easy_init
.
我建议您改用配置.您可以在代码中嵌入配置:
I suggest you to use configuration instead. You can embed configuration in you code:
use strict; use warnings;
use Log::Log4perl;
Log::Log4perl->init(\<<CONFIG);
log4perl.rootLogger = DEBUG, screen, file
log4perl.appender.screen = Log::Log4perl::Appender::Screen
log4perl.appender.screen.stderr = 0
log4perl.appender.screen.layout = PatternLayout
log4perl.appender.screen.layout.ConversionPattern = %d %p> %F{1}:%L %M - %m%n
log4perl.appender.file = Log::Log4perl::Appender::File
log4perl.appender.file.filename = 1.log
log4perl.appender.file.mode = append
log4perl.appender.file.layout = PatternLayout
log4perl.appender.file.layout.ConversionPattern = %d %p> %F{1}:%L %M - %m%n
CONFIG
my $logger = Log::Log4perl->get_logger();
$logger->info("my message");
这篇关于log4perl 如何同时写入 STDERR 和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!