how to set loglevel from INFO to ERROR using log4j2 api at runtime?

Nandan picture Nandan · Jun 19, 2013 · Viewed 12k times · Source

logger.setLevel() method is not available in log4j2 API. So how to set log level at run time.

Answer

amcintosh picture amcintosh · Aug 23, 2013

I'm not sure if this is the best way, but you set the level on org.apache.logging.log4j.core.config.LoggerConfig which you can get from the LoggerContext via the LogManager.

Once set, you can update the loggers with the new configuration.

As an example:

public static void main(String[] args) {
    Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
    log.error("An error");
    log.debug("A debug");

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration conf = ctx.getConfiguration();
    conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(Level.DEBUG);
    ctx.updateLoggers(conf);

    log.error("Another error");
    log.debug("Another debug");
}

Yields:

14:03:41.346 [main] ERROR  - An error
14:03:41.348 [main] ERROR  - Another error
14:03:41.348 [main] DEBUG  - Another debug