Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j2 Web Lookup not working

We have Spring java-based web deployments which use log4j2.xml for logging messages to files, etc.

We now need to update our log4j2.xml configs in order to be able to do a ${web:contextPath} web lookup inside them so that we can use a deployment's context name as part of the log file's name which the loggers log messages to. However, when we deploy the apps, the log4j2 configurations fail to recognise any web lookup related stuff. The file created to log messages to is simply created with the name ${web and no messages are actually logged in them.

I have read various docs online related to log4j2 web lookups when running in 3.0 servlets but I still can't see what the problem might be in our configurations. And I don't know what to look for in the log4j's trace logs in order to see what it is that we are missing.

Our Stack:

Windows and Linux OSes Java 8 Tomcat 7.0.5x log4j-xxx 2.2 (log4j-api, log4j-core, log4j-slf4j-impl, log4j-jcl, log4j-web all in classpath)

Any help on how to get web lookups to work is much appreciated.

Cheers, PM

like image 780
Going Bananas Avatar asked Sep 29 '22 08:09

Going Bananas


1 Answers

If you have a Spring 4 java annotation based web application, it is possible to have log4j-slf4j-impl jar in the classpath and still do a log4j2 web lookup by having your web initialization class extend Log4jServletContainerInitializer and calling super.onStartup() on it.

Example:

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.apache.logging.log4j.web.Log4jServletContainerInitializer;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

public class WebInitialiser extends Log4jServletContainerInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext)
            throws ServletException {

        super.onStartup(null, servletContext);

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

        rootContext.register(ApplicationConfig.class, IntegrationConfig.class,
                JmsConfig.class, JmxConfig.class);

        servletContext.addListener(new ContextLoaderListener(rootContext));
    }

}

Note however that you still seem to need to have your web.xml include a <display-name> node in order for log4j2 web lookups to work on a Tomcat 7.0.5x container.

For more detail on all this, see the answers that I got in the log4j user mailing list thread:

log4j2 web lookup questions

Cheers, PM.

like image 79
Going Bananas Avatar answered Oct 18 '22 13:10

Going Bananas