Search code examples
spring-mvclog4j2spring-java-config

What is right way to supply initialization for log4j2 in a Spring MVC Webapp using Java Config and no web.xml?


I have a Spring MVC Web App (4.0) with log4j2. This webapp uses no web.xml and takes care of configuration through Java Config. Log4j2 configuration needs to take place in an external config file, not on the classpath.

In a previous incarnation with web.xml we had

<context-param>
    <param-name>log4jConfiguration</param-name>
    <param-value>file:///path/to/log4j2.xml</param-value>
</context-param> 

and this worked.

In the new web.xml-less world, I tried this:

public class WebappInitializer 
extends AbstractAnnotationConfigDispatcherServletInitializer 
{

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("WebappInitializer.onStartup()");
        servletContext.setAttribute("log4jConfiguration", "file:///path/to/log4j2.xml");

This does not work. It seems to happen too late and in any event doesn't work. The logs show:

ERROR StatusLogger No Log4j context configuration provided. This is very unusual.
WebappInitializer.onStartup()

and no log4j logging occurs.

What is the right way to replace this context-param declaration with web.xml in a web.xml-less Spring MVC app?

UPDATE:

I can make this problem go away by adding the following web.xml:

<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
          version="3.0">

    <context-param>
        <param-name>log4jConfiguration</param-name>
        <param-value>file:///path/to/log4j2.xml</param-value>
    </context-param> 

</web-app>

Surely, there must be a better way!


Solution

  • I believe you can reconfigure log4j2 to a new config file during runtime like this.

         LoggerContext context = (LoggerContext)LogManager.getContext(false);
         context.setConfigLocation(URI.create("path to file"));
         context.reconfigure();
    

    Could just add this to your onStartup.