8

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?

Community
  • 1
  • 1

1 Answers1

12

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.

StackzOfZtuff
  • 2,534
  • 1
  • 28
  • 25
D.B.
  • 4,523
  • 2
  • 19
  • 39