Configure Log4j's appender to display in the log console from Error and save to logs file from Info

0

Good evening guys.

I need to display in the console only logs from Error and write to logs file from Info.

I have tried to use the additivity property for false, but when I use it the appender stops working and I also tried using Stackoverflow responses, but it did not work.

Dependency used:

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

log4j.properties:

log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=INFO, debugLog
log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

HelloWorld.java:

package com.vaannila.helloworld;

import org.apache.log4j.Logger;

public class HelloWorld {

private static final Logger logger = Logger.getLogger(HelloWorld.class);

    public static void main(String[] args) {
        logger.debug("Sample debug message");
        logger.info("Sample info message");
        logger.warn("Sample warn message");
        logger.error("Sample error message");
        logger.fatal("Sample fatal message");
    }
}

The only way I could do this was by setting the rootLogger as Info and an appender with a log up, but what I need is the reverse.

Is there a way to do this?

    
asked by anonymous 23.05.2017 / 03:28

1 answer

1

The problem is in the configuration of log4j log4j.properties

In order to configure it correctly, I recommend that you always set the lowest level ( rootLogger ) to all appenders that you are going to use, then when you configure each appender to use DEBUG to specify the level the appender will join.

I think the following setup will solve your problem:

#Cria os dois appender para o nível mais baixo de log
log4j.rootLogger=DEBUG, console, file

#Configura o console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=ERROR
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

#Configura o fileAppender
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.Threshold=INFO
log4j.appender.file.File=debug.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n
    
23.05.2017 / 04:17