Warm tip: This article is reproduced from serverfault.com, please click

log4perl: How to write ERROR message to file and DEBUG message to stderr?

发布于 2020-11-29 08:11:34

I want to write ERROR message to a file, and write DEBUG message to stderr, then I write the following code:

#!/usr/bin/perl

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

Log::Log4perl->easy_init(
        {
            file  => ">> error_log",
            level => $ERROR,
        },
        {
            file  => "STDERR",
            level => $DEBUG,
        }
        );

ERROR( "ERROR MESSAGE" );
DEBUG( "DEBUG MESSAGE" );

When I run the above code, the message ERROR MESSAGE and DEBUG MESSAGE write to both file and stderr, can anyone explain why?

Questioner
Ren
Viewed
22
Håkon Hægland 2020-11-29 21:23:37

To achieve both output to file and screen for different levels and the same category, you can use a custom filter. For example:

use feature qw(say);
use strict;
use warnings;
use Log::Log4perl qw(:easy);

my $conf   = <<'EOF';
log4perl.rootLogger             = DEBUG, file, screen
log4perl.filter.MatchDebug = Log::Log4perl::Filter::LevelMatch
log4perl.filter.MatchDebug.LevelToMatch  = DEBUG
log4perl.filter.MatchDebug.AcceptOnMatch = true

log4perl.filter.MatchError = Log::Log4perl::Filter::LevelMatch
log4perl.filter.MatchError.LevelToMatch  = ERROR
log4perl.filter.MatchError.AcceptOnMatch = true

log4perl.appender.file          = Log::Log4perl::Appender::File
log4perl.appender.file.filename = error_log.txt
log4perl.appender.file.mode     = append
log4perl.appender.file.utf8     = 1
log4perl.appender.file.Filter   = MatchError
log4perl.appender.file.layout   = SimpleLayout

log4perl.appender.screen         = Log::Log4perl::Appender::Screen
log4perl.appender.screen.stderr  = 1
log4perl.appender.screen.utf8    = 1
log4perl.appender.screen.Filter   = MatchDebug
log4perl.appender.screen.layout   = SimpleLayout
EOF

Log::Log4perl::init( \$conf );
ERROR( "ERROR MESSAGE" );
DEBUG( "DEBUG MESSAGE" );

See also How to set two appenders with different log levels in Log::Log4perl?