If you have a web application which you want to deploy more than once to a single servlet container you have the problem of separating your log files for the different web app instances. This is because the log configuration file is located in your WAR-file and it is not easy to change this file during the build process.
But there is a simple way of defining the log filename based on the context path of your web application. Simply set the contextPath as a system property in a ServletContextListener:
public class ContextDependentInitializer implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); String contextPath = context.getContextPath(); System.setProperty("contextPath", contextPath); } }
After that you have to declare the listener in your web.xml as follows:
<web-app> <listener> <listener-class>de.oio.logging.ContextDependentInitializer</listener-class> </listener> </web-app>
Then you are able to use the context path name to define the log filename in your Log4J configuration file. For example:
log4j.appender.LOG.file=${catalina.base}/logs/${contextPath}.log


this does not work for me.
The listener works fine, but the contextPathis not written into the Log4J config file. Therefore my logs are named …/logs/.log
Any suggestions?
Are you using Log4J 2.0? The Property Substitution mechanism changed a little bit in the new version. Look at the documentation: https://logging.apache.org/log4j/2.0/manual/configuration.html#PropertySubstitution
I guess you have to use ${sys:contextPath} instead but I haven’t tried this.
‘${sys:contextPath}’ solved it. Thank you!
With log4j 2 there is the the lookup “web:contextPath”, so this is handy:
fileName=”${sys:catalina.base}/logs/${web:contextPath}.log”
See: https://logging.apache.org/log4j/2.0/manual/lookups.html#WebLookup