Ole Ole - 5 months ago 39
Java Question

Configuring a Logger Programmatically with Log4J 2?

With SLF4J I can get a logger from a class and configure the logging level like this:

private static Logger logger = (Logger) LoggerFactory.getLogger(SomeClass.class.getName());
logger.setLevel(Level.TRACE);


How do I do the same with log4j 2?

Answer

You do this:

// 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);

See the FAQ: https://logging.apache.org/log4j/2.x/faq.html#reconfig_level_from_code

Gary