Reputation: 46890
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?
Upvotes: 5
Views: 695
Reputation: 9141
First, the support for setLevel is NOT provided by SLF4J - the SLF4J Logger interface does not have a setLevel method. As an API, SLF4J has absolutely no knowledge of how a logging implementation performs configuration.
If you look at your sample code you will see the cast to Logger - this is an ch.qos.logback.classic.Logger, which means you are tied to Logback when you do this.
Gary's answer is correct and it highlights one of the fundamental differences between Log4j 2 and Logback. With Logback the configuration is intimately tied to the same Logger you get from the LoggerFactory. With Log4j you are modifying the level through the configuration, which is completely separate from the Loggers the application obtains.
Upvotes: 4
Reputation: 546
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
Upvotes: 4