3

我试图设置两个附加程序,但它似乎只写入 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);
4

2 回答 2

5

与自定义附加程序混合不是一个好主意easy_init。您可以通过将 appender 添加到 logger 来解决此问题$logger->add_appender($appender)。但这会导致消息重复,因为您已经在easy_init.

我建议您改用配置。您可以在代码中嵌入配置:

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");
于 2011-09-08T22:48:21.490 回答
4

Log::Log4Perl 文档在“Stealth Logger”部分的中途给出了答案: http ://search.cpan.org/~mschilli/Log-Log4perl-1.49/lib/Log/Log4perl.pm#Stealth_loggers

use Log::Log4perl qw(:easy);

Log::Log4perl->easy_init( { level    => $DEBUG,
                            file     => ">>test.log",
                            layout   => '%F{1}-%L-%M: %m%n' },
                          { level    => $DEBUG,
                            file     => "STDOUT",
                            layout   => '%m%n' },
                        );

我有同样的问题......即使在发布后 5 年,当搜索“perl log4perl 写入文件和屏幕”时,它仍然在谷歌的首页

于 2017-07-15T00:51:59.090 回答