Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the AppenderRef Level in log4j2 programmatically?

Tags:

java

log4j2

How can I change the AppenderRef Level in log4j2?

There is a stackoverflow question (with answer) where this was solved non-programmatically. I want the same but programmatically instead. There is only a get method in AppenderRef to retrieve the Level but no method to set it.

So, is there any way to set the Level in the AppenderRef in log4j2 programmatically?

like image 364
Michael Langhammer Avatar asked Mar 08 '17 21:03

Michael Langhammer


People also ask

What is root level in log4j2?

Configuration: the root element of a log4j2 configuration file; the status attribute represents the level at which internal log4j events should be logged. Appenders: this element contains a list of appenders; in our example, an appender corresponding to the System console is defined.


1 Answers

You have to do it by removing the appender and then adding it again with the desired level.

Example log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="logFile" fileName="log.txt" immediateFlush="false"
            append="true">
            <PatternLayout
                pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>

    <Loggers>
        <Root level="trace">
            <AppenderRef ref="logFile" level="info" />
        </Root>
    </Loggers>
</Configuration>

Example code:

package example;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;

public class Log4j2SetAppenderRefLvlMain {
    private static final Logger log = LogManager.getLogger();

    public static void main(String[] args) {
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final Configuration config = ctx.getConfiguration();


        log.info("Before altering the appender!");

        LoggerConfig rootLoggerConfig = config.getLoggers().get("");
        rootLoggerConfig.removeAppender("logFile");
        rootLoggerConfig.addAppender(config.getAppender("logFile"), Level.WARN, null);
        ctx.updateLoggers();

        log.info("After altering the appender!");
        log.warn("After altering the appender!");
    }

}

Output:

2017-04-13 21:04:20.892 [main] INFO  example.Log4j2SetAppenderRefLvlMain - Before altering the appender!
2017-04-13 21:04:20.895 [main] WARN  example.Log4j2SetAppenderRefLvlMain - After altering the appender!

Notice how only the WARN level message is printed to the log after we changed the appender level to WARN. This proves that it works.

like image 79
D.B. Avatar answered Oct 05 '22 19:10

D.B.