0

We can externalize log4j2.properties file using system property -Dlog4j2.configurationFile=<file_path>, However, there are multiple web apps deployed on the same server, So, I want to explicitly set the file path for my web app only. One way is to use the below code. However, LoggerContext is a private API that can change in minor releases. Is there any easy way (without java code) to set web application-specific (or to say external log4j2.properties per web-app) external log4j2.properties file ?

// import org.apache.logging.log4j.core.LoggerContext;

LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File("path/to/a/different/log4j2.xml");

// this will force a reconfiguration
context.setConfigLocation(file.toURI());

1 Answers1

0

If you add log4j-web to your application, additional features specific to web applications will be present (cf. documentation).

In your specific case your can use the log4jConfiguration servlet context parameter to specify the location of the config file of that particular application. How to externally specify a servlet context parameter depends on your servlet container.

For example in Tomcat you can do it in a context.xml file:

<Context>
    <Parameter name="log4jConfiguration" value="/path/to/config/file" override="false"/>
    ...
</Context>

Remark: org.apache.logging.log4j.core.LoggerContext is not an internal class, it is just a class from Log4j Core (the official implementation of the Log4j API), whereas org.apache.logging.log4j.LoggerContext belongs to Log4j API. Unless you switch implementations from Log4j Core to another, a LoggerContext will always be a core.LoggerContext.

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43