Search code examples
perllog4perl

Log4perl: separate INFO and ERROR files using easy_init


I am currently sending INFO and above to STDOUT using:

Log::Log4perl->easy_init({level=>("$INFO"), layout=>"%d %p - %m%n", file=>"STDOUT"});

How can I send ERROR and above to STDERR?


Solution

  • This task is probably too much for easy_init setup, because you need to use filters to achieve that effect. With normal setup you can do this:

    use Log::Log4perl qw(:easy);
    
    Log::Log4perl->init(\ qq{
        log4perl.logger = INFO, AppInfo, AppError
    
        # Filter to match level ERROR
        log4perl.filter.MatchError = Log::Log4perl::Filter::LevelMatch
        log4perl.filter.MatchError.LevelToMatch  = ERROR
        log4perl.filter.MatchError.AcceptOnMatch = true
    
        # Filter to match level INFO
        log4perl.filter.MatchInfo  = Log::Log4perl::Filter::LevelMatch
        log4perl.filter.MatchInfo.LevelToMatch  = INFO
        log4perl.filter.MatchInfo.AcceptOnMatch = true
    
        # Error appender
        log4perl.appender.AppError = Log::Log4perl::Appender::Screen
        log4perl.appender.AppError.stderr   = 1
        log4perl.appender.AppError.layout   = SimpleLayout
        log4perl.appender.AppError.Filter   = MatchError
    
        # Info appender
        log4perl.appender.AppInfo = Log::Log4perl::Appender::Screen
        log4perl.appender.AppInfo.stderr   = 0
        log4perl.appender.AppInfo.layout   = SimpleLayout
        log4perl.appender.AppInfo.Filter   = MatchInfo
    });
    
    ERROR "Error";
    INFO "Info";