apache / logging-log4j2

Apache Log4j 2 is a versatile, feature-rich, efficient logging API and backend for Java.
https://logging.apache.org/log4j/2.x/
Apache License 2.0
3.31k stars 1.57k forks source link

Document isLog4jAutoShutdownDisabled to enable logging during a web application listener's contextDestroyed #2689

Open krallus opened 1 week ago

krallus commented 1 week ago

As discussed in issue LOG4J2-1606, a flag was added to address the problem of log4j-web shutting down Log4j when other listeners defined in the web app still want to log messages during their contextDestroyed. However, this is not documented anywhere and it was quite difficult for me to find the solution. I suggest documenting this in Using Log4j 2 in Web Applications or Frequently Asked Questions:

When your web application includes log4j-web (as it should) and you would like to use Log4j to log messages when one of your listener's contextDestroyed method is called, include the following near the top of your web.xml:

<context-param>
    <!-- auto-shutdown stops log4j when the web fragment unloads, but that is too early because it is before 
        the listeners shut down. To compensate, use a Log4jShutdownOnContextDestroyedListener and register it before 
        any other listeners which means it will shut down *after* all other listeners. -->
    <param-name>isLog4jAutoShutdownDisabled</param-name>
    <param-value>true</param-value>
</context-param>

<listener>
    <!-- ensure logging stops after other listeners by registering the shutdown listener first -->
    <listener-class>org.apache.logging.log4j.web.Log4jShutdownOnContextDestroyedListener</listener-class>
</listener>

Note that for Servlet 3.x, you don't need to include your listener in your web.xml if it is annotated with @WebListener. The above solution will still work for you.

ppkarwasz commented 1 week ago

Hi @krallus,

Since Log4j 2.21.0 you don't need to disable the automatic shutdown, you only need to register manually an (additional) Log4jServletListener as first listener in a web.xml descriptor:

<listener>
  <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

See #1784 for details.

We are currently in the process of rewriting our documentation page. A note about the order of context listeners is already present in the 3.x staging site and we will soon backport the documentation changes to 2.x (see #2547).

krallus commented 1 week ago

Thank you for sharing your solution, @ppkarwasz. It did not appear as a result in any of my searches. I can confirm that your solution works for me, both during web app undeploy and during server shutdown. I tested this on Tomcat 9+Java 8, Servlet 3.1, and Log4j 2.23.1, with log4j-web included.