Log :: Log4Perl取决于LogLevel

时间:2019-02-28 13:27:12

标签: perl log4perl

我的目标是将“调试”消息(以及后续级别:信息,警告,致命等)记录到文件中,但仅将“警告” /致命/错误记录到屏幕上。 两者都在同一时间。

我尝试了easy_init("stealth logging"):

Log::Log4perl->easy_init(
    { level => $DEBUG, file => ":utf8> ./log_" . basename($0) . "_.log" },
    { level => $WARN, file => 'STDOUT' },
);

...但是第二个定义的level会覆盖常规日志级别。

if (false){
    WARN "some bad thing";  # print this to the screen AND to the file
}else{
    do_something;
    DEBUG "doing something";    # print this just to the file
    if (bla){WARN "another bad thing"}
}

在这种情况下,警告会显示在屏幕上并且文件正确,但是不会显示“ DEBUG”(调试)消息(Perl 5.26)

{ level => $DEBUG ...行放在{level => $WARN ...行之后,然后将所有警告和调试消息打印在屏幕上并显示在文件上。

有人可以指导我,该怎么做(即使可能的话)?我需要澄清吗?

1 个答案:

答案 0 :(得分:2)

以下perl最小工作示例:

  • 打印到文件DEBUG和更高级别
  • 打印到屏幕警告和更高级别

我没有使用easy_init,因为详细配置更加详细。我在脚本中有注释,描述了配置在做什么。让我知道是否需要更多细节。

use strict;
use Log::Log4perl qw(:easy);

# rootlogger prints to "Logfile" and "Screen"
# "Logfile" and "Screen" are then defined with the proper appender (File and Screen)
# and the proper Threshold is used to limit what goes in each appender

my $conf = q(
log4perl.rootLogger=DEBUG,Logfile,Screen

log4perl.appender.Logfile           = Log::Log4perl::Appender::File
log4perl.appender.Logfile.filename  = /home/USER/test.log
log4perl.appender.Logfile.mode      = append
log4perl.appender.Logfile.utf8      = 1
log4perl.appender.Logfile.Threshold = DEBUG
log4perl.appender.Logfile.recreate  = 1
log4perl.appender.Logfile.layout    = Log::Log4perl::Layout::SimpleLayout

log4perl.appender.Screen            = Log::Log4perl::Appender::Screen
log4perl.appender.Screen.stderr     = 0
log4perl.appender.Screen.Threshold  = WARN
log4perl.appender.Screen.layout     = Log::Log4perl::Layout::SimpleLayout
);
Log::Log4perl::init( \$conf );

my $logger = Log::Log4perl->get_logger( 'foo' );

WARN "some bad thing";      # print this to the screen AND to the file
DEBUG "doing something";    # print this just to the file
~ $ perl log4perl.pl
WARN - some bad thing

~ $ cat test.log 
WARN - some bad thing
DEBUG - doing something

版本

我测试过:

  • 操作系统:Ubuntu 14.04.5 LTS
  • perl:v5.18.2
  • Log :: Log4perl:1.49(和1.41)