7
votes

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 ?

2

2 Answers

4
votes

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.

3
votes

Got my answer here: Configuring log4j2 and log4j using a single log4j2 xml file

Basically, we need to use log4j-1.2-api-2.0.jar to route all calls that our application makes to log4-1.2 API to log4j2 implementation.