Using the context path of a web-app as log filename with Log4J

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
Short URL for this post: http://wp.me/p4nxik-1zW
This entry was posted in Build, config and deploy and tagged , , . Bookmark the permalink.

4 Responses to Using the context path of a web-app as log filename with Log4J

  1. Sebastian says:

    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?

  2. 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.

  3. Sebastian says:

    ‘${sys:contextPath}’ solved it. Thank you!

  4. Markus says:

    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

Leave a Reply