0

I'm using log4j2 and trying to change the log level at runtime. I've seen other similar posts here and here but still can't get it to work

Here is my code:

public static void main(String[] args)
{
        Logger log = LogManager.getLogger(LogManager.getLogger(Main.class.getName()).getName());

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.getLogger(Main.class.getName()).getName()); 

        loggerConfig.setLevel(Level.DEBUG);
        ctx.updateLoggers(config);

        log.trace("trace");
        log.debug("debug");
        log.info("info");

        loggerConfig.setLevel(Level.TRACE);
        ctx.updateLoggers(config);

        log.trace("trace");
        log.debug("debug");
        log.info("info");
    }
}

The log level is set to INFO in the config file. The console output is:

info
info

UPDATE

I've realised that the log level is successfully changing in the log file but not in the console.

Here is a snippet from the config file in case it helps:

<Configuration status="info">
<Loggers>
    <Root level="debug">
        <AppenderRef ref="Console" level="INFO" />
        <AppenderRef ref="LogFile" />
    </Root>
</Loggers>
Community
  • 1
  • 1
ksl
  • 4,519
  • 11
  • 65
  • 106

1 Answers1

0

The attribute level on an appender is a filter for the appender : all log with lower levels are not considered by this appender, but it is not the level of the logger

Remove the filter on console appender and keep only the level on the logger should work fine

Prim
  • 2,880
  • 2
  • 15
  • 29
  • I don't really understand your comment about filters (despite reading up on it) but your suggestion worked. Thanks. – ksl Nov 24 '15 at 11:35