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

Asked

Viewed 1,045 times

0

Good evening, everyone.

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

I’ve tried using the additivity property for false, but when using it the appender stops working and also tried using Stackoverflow responses, but it didn’t 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 was by defining rootLogger as Info and an appender with a log above, but what I need is the opposite.

There’s a way to do it?

1 answer

1


The problem is in the log4j configuration log4j.properties

To set it up properly recommend setting in rootLogger always the lowest level (DEBUG) for all the appenders that you will use, then when you will configure each appender use the Threshold to specify the level the appender will join.

I think the following setting 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.