Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add appender to Logger in Log4j2

In Log4j 1.2, you could simply take a logger and add an appender at runtime. This was handy for test purposes for instance. We used to create a mock appender and add it to the logger. Subsequently we could make different assertions.

What is the equivalent thing with log4j2?

This example for instance shows how other people were adding test appenders.

The log4j2 page shows a few examples on how to add appenders. However, they add appenders to the overall context. Which seems different from adding appenders for one specific logger.

Another observation is that if you use org.apache.logging.log4j.core.Logger as opposed to org.apache.logging.log4j.Logger, you can still add appenders. However most people use org.apache.logging.log4j.Logger. And in fact, LogManager returns an instance of org.apache.logging.log4j.Logger. So, I am not sure how to connect these two classes and whether they should be connected at all.

Another observation is that if I call

      LogManager.getContext().getConfiguration().getLoggers()

I can get a ist of all LoggerConfig objects in the context. I subsequently add appenders to any LoggerConfig object. The question however is, how do I get the LoggerConfig related to an instance of org.apache.logging.log4j.Logger?

This is confusing me.

like image 236
Klaus Avatar asked Jul 07 '16 09:07

Klaus


1 Answers

org.apache.logging.log4j.Logger is an interface located in the log4j-api module. org.apache.logging.log4j.core.Logger is a concrete class (implementing the above interface) which lives in the log4j-core module.

LogManager (also in the log4j-api module) returns something that implements the org.apache.logging.log4j.Logger interface, and if the log4j-core module is in the classpath this will be an instance of org.apache.logging.log4j.core.Logger.

So you can cast the returned Logger to org.apache.logging.log4j.core.Logger and add the Appender.

Each core Logger has a LoggerConfig (1-to-1 relationship). You can find the LoggerConfig that corresponds to the desired Logger because they have the same name.

like image 59
Remko Popma Avatar answered Sep 21 '22 16:09

Remko Popma