Question

I want to try and use logj 2 in my web application. With log4j 1.x, we set-up different configuration files based on environment and use ServletContextListener to load the appropriate configuration using a call like

DOMConfigurator.configureAndWatch(logConfigFile, delay);

by passing the config file location.

I was planning on doing the same for log4j2 config file but according to this and this, it is not possible or advisable to use DOMConfigurator with log4j2.

So, my question is: How can I use different configuration files based on environment with log4j 2?

Was it helpful?

Solution 2

Thanks to Remko Popma, I posted the question and got an answer from log4j user mailing list. One can use a System property or environment variable with 'log4jconfiguration' context-param to dynamically set the configuration file at runtime

OTHER TIPS

What do you want to achieve with having multiple config files? I'll take a guess that you want to have separate log files for each web application.

One way you can achieve this is using the RoutingAppender; this can delegate log events to other appenders depending on key/values set in the ThreadContextMap. Some people use their web app name as the value to switch on.

Beta-9 (the last beta before GA) will be released soon and it will have better docs for using log4j2 with web apps (and the FAQ will have a detailed RoutingAppender example).

Does this answer your question?

If you are in a Servlet 3.x container, I would recommend going with what Log4j2 recommends by adding the log4j-web jar to the others being used and setting the Context Parameters as stated in the log4j2 usage manual for web applications.

The mailing list link in the answer is broken. Although it is currently accessible here. For a full answer, you can use a system property in the context param like this:

<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>file:/${sys:MYLOGDIR}/log4j2.xml</param-value>
</context-param>

This one was really hard to find as it is only mentioned in the mailing list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top