Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route 3rd party libraries' Log4j logging to Log4j2

My Java application which uses Log4j2 as its logging implementation has dependency on a 3rd party library which uses Log4j.

I am trying to set root logger appender and log level programatically in my application (using code below) for these 3rd party loggers, but these 3rd party library's loggers are still not logging to myAppender:

LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
LoggerConfig loggerConfig = ctx.getConfiguration().getLoggerConfig(
        LogManager.ROOT_LOGGER_NAME);
loggerConfig.addAppender(myAppender, Level.ERROR, null);
ctx.updateLoggers();

A solution I thought of was to use Log4jToSLF4JAdaptor to route log4j's logging to SLF4J and then use Log4JSLF4JImpl to route SLF4J's logging to my Log4J2 implementation but as stated here (https://logging.apache.org/log4j/2.0/log4j-slf4j-impl/index.html), it would lead to endless routing.

Can you please suggest how can I route logging of these 3rd party library's loggers to myAppender ?

like image 424
Vijay Kansal Avatar asked Sep 29 '15 07:09

Vijay Kansal


People also ask

Can we use log4j and Log4j2 together?

Log4j 2 provides support for the Log4j 1 logging methods by providing alternate implementations of the classes containing those methods. These classes may be found in the log4j-1.2-api jar distributed with the project.

What is difference between log4j and Log4j2?

Community support: Log4j 1. x is not actively maintained, whereas Log4j 2 has an active community where questions are answered, features are added and bugs are fixed. Automatically reload its configuration upon modification without losing log events while reconfiguring.


1 Answers

For 3rd party libraries using the Log4j 1.x API: In addition to the log4j-api and log4j-core jar files, you need to add the log4j-1.2-api jar file to your classpath.

For 3rd party libraries using the SLF4J API: add log4j-api, log4j-core and the log4j-slf4j-impl jar files to your classpath (you also need the slf4j API jar).

For 3rd party libraries using JUL (java.util.logging): add log4j-api, log4j-core and the log4j-jul jar files to your classpath, as well as set the system property java.util.logging.manager to org.apache.logging.log4j.jul.LogManager.

like image 140
Remko Popma Avatar answered Nov 18 '22 06:11

Remko Popma