Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

log4j2

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

like image 296
Nandan Avatar asked Jun 19 '13 08:06

Nandan


People also ask

How do you change the log level in Log4j2 at runtime?

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. If you wish to change the root logger level, do something like this : LoggerContext ctx = (LoggerContext) LogManager.

How do you change the log level in slf4j?

When using log4j, the Logger. log(Priority p, Object message) method is available and can be used to log a message at a log level determined at runtime. We're using this fact and this tip to redirect stderr to a logger at a specific log level. slf4j doesn't have a generic log() method that I can find.

What is configuration status 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.


2 Answers

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
like image 174
amcintosh Avatar answered Oct 04 '22 00:10

amcintosh


Credit to amcintosh, I wrapped their answer in a function:

/** Override the logging level of a given logger, return the previous level */
public static Level setLevel(Logger log, Level level) {
  LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
  Configuration conf = ctx.getConfiguration();
  LoggerConfig lconf = conf.getLoggerConfig(log.getName());
  Level oldLevel = lconf.getLevel();
  lconf.setLevel(level);
  ctx.updateLoggers(conf);
  return oldLevel;
}

Despite amoe's comment, this seems to be working correctly for me using Log4J 2.5.

like image 37
dimo414 Avatar answered Oct 04 '22 01:10

dimo414