Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configuring a Logger Programmatically with Log4J 2?

Tags:

java

log4j2

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?

like image 810
Ole Avatar asked Jun 27 '16 22:06

Ole


People also ask

How do I use Apache log4j 2?

There are many ways to use Log4j2 configuration in you application. Using a configuration file written in XML, JSON, YAML or properties file. Programmatically, by creating a configuration factory and configuration implementation. Programmatically, by calling APIs exposed in the configuration interface.

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

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

like image 196
Gary Gregory Avatar answered Sep 28 '22 18:09

Gary Gregory


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.

like image 20
rgoers Avatar answered Sep 28 '22 18:09

rgoers