javalog4j2

Programmatically change log level in Log4j2


I'm interested in programmatically changing the log level in Log4j2. I tried looking at their configuration documentation but that didn't seem to have anything. I also tried looking in the package: org.apache.logging.log4j.core.config, but nothing in there looked helpful either.


Solution

  • The Easy Way :

    EDITED according to log4j2 version 2.4 FAQ

    You can set a logger’s level with the class Configurator from Log4j Core. BUT be aware that the Configurator class is not part of the public API.

    // org.apache.logging.log4j.core.config.Configurator;
    Configurator.setLevel("com.example.Foo", Level.DEBUG);
    
    // You can also set the root logger:
    Configurator.setRootLevel(Level.DEBUG);
    

    Source

    The Preferable Way :

    EDITED to reflect changes in the API introduced in Log4j2 version 2.0.2

    If you wish to change the root logger level, do something like this :

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); 
    loggerConfig.setLevel(level);
    ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.
    

    Here is the javadoc for LoggerConfig.