Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

logging

perl

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?

like image 677
Ren Avatar asked Oct 25 '25 01:10

Ren


1 Answers

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?

like image 133
Håkon Hægland Avatar answered Oct 26 '25 16:10

Håkon Hægland