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:


Then you are able to use the context path name to define the log filename in your Log4J configuration file. For example:

Short URL for this post:
This entry was posted in Build, config and deploy and tagged , , . Bookmark the permalink.

5 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:
    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:



  5. Matteo T says:

    System.setProperty are system wide so it isn’t a good practice in an application server where multiple webapps are running.

Leave a Reply to Sebastian Cancel reply

Your email address will not be published. Required fields are marked *