Specifying An External Log4j2.xml File Per WAR

Viewed 187

I have an application that deploys 4 separate war files, each requiring a customized log4j2.xml file (this makes using -Dlog4j.configurationLocation=_____ impractical).

What I need to do is to be able to configure these on a per-WAR basis, in a filesystem location named /application/config/. This should be possible via the servlet initializer as such:

    @Override
    public void onStartup(ServletContext servletContext) {
        // other code
        servletContext.setInitParameter("log4jConfiguration", "file:/application/config/log4j2-module1.xml");
        // other code
    }

I have added log4j-web to the POM, but I'm still having no luck. I've looked through all of the other people asking similar questions, and nothing. I've also created a Listener specifically to initialize log4j, and still nothing.

Can anyone point out what I'm doing wrong? This is a Spring (but not Spring Boot) application, so I can't just make a change to application.properties.

1 Answers

If you look at the web-fragment.xml from log4j-web, you'll notice that it is ordered before any other fragments. This is intentional: logging is usually the first service you need to initialize. That explains why your WebApplicationInitializers are executed too late.

To configure multiple web applications I would use "convention over configuration" and add a file called log4j2<context name>.xml in either the WEB-INF folder or the application's classpath.

The context name is the first non empty value between:

  1. The log4jContextName servlet parameter,
  2. The value of <display-name>,
  3. The context path.

If you want to follow a different convention, you can add a log4j2.configurationFile property to a log4j2.component.properties file on the application's classpath.

Related