Java – set an absolute path for a “” file


I am using apache commons + log4j for my web app.

normally log4j needs a configuration file inside the classpath; but I need to delegate the logging configuration to an external file (I need to deploy a .war in an environment, but the log configurations (max size, position, etc) it's up to a second team.

I have a in my classpath

# log4j.configuration=/absolute/path/where/external/logs/are/

unfortunately, the commented line doesn't work.

Is there a way to set up log4j with an external configuration file?

Best Solution

You can set it as a system property log4j.configuration property .. for example in J2SE app

java -Dlog4j.configuration=file:/path/to/ myApp

Note, that property value must be a URL.

For more read section 'Default Initialization Procedure' in Log4j manual.

It's also possible letting a ServletContextListener set the System properties:

import java.util.Enumeration;
import javax.servlet.*;

public class SystemPropertiesHelper implements
        javax.servlet.ServletContextListener {
    private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();
        Enumeration<String> params = context.getInitParameterNames();

        while (params.hasMoreElements()) {
          String param = (String) params.nextElement();
          String value = 
          if (param.startsWith("customPrefix.")) {
              System.setProperty(param, value);

    public void contextDestroyed(ServletContextEvent event) {

And then put this into your web.xml (should be possible for context.xml too)



I got this from this listener code from answer .

I hope this could help you!

Related Question