Logging from servlet context destroyed event
Asked Answered
T

2

6

Within my Servlet-based application, I would like to log events for startup and shutdown.

I've tried to implement the ServletContextListener interface to do this:

public class DiagnosticListener
    implements ServletContextListener {

    private static final Logger LOG = LogManager.getLogger(DiagnosticListener.class);

    @Override
    public void contextInitialized( final ServletContextEvent sce ) {
        LOG.info("Context initialized.");
    }

    @Override
    public void contextDestroyed( final ServletContextEvent sce ) {
        LOG.info("Context destroyed.");
    }
}

The initialized event is logged as expected, but the destroyed event never appears. I am assuming this is to do with how log4j2 manages its lifecycle using a similar listener, that logging infrastructure is no longer available during this event.

Is there a way to log an event for the application being shut down?

That answered 1/6, 2016 at 0:43 Comment(0)
E
8

We clashed against a similar issue with Logback. You have to write your own web.xml to fix that, because there's no alternatives to define listeners order.

We disabled the LogbackServletContextListener with:

<context-param>
    <param-name>logbackDisableServletContainerInitializer</param-name>
    <param-value>true</param-value>
</context-param>

then add the LogbackServletContextListener by hand as the first listener:

<listener>
    <listener-class>ch.qos.logback.classic.servlet.LogbackServletContextListener</listener-class>
</listener>

and then all the other listeners.

No idea about log4j, but I think there's something similar...

edit: yes, there is:

<context-param>
    <param-name>isLog4jAutoInitializationDisabled</param-name>
    <param-value>true</param-value>
</context-param>

source: https://logging.apache.org/log4j/2.x/manual/webapp.html

Ebberta answered 13/4, 2018 at 11:31 Comment(1)
Is there also a possibility to set this using the tomee maven plugin ?Landahl
S
0

If you configured Log4j's ServletContextListener before yours in web.xml then Log4j should be initialized before your ServletContextListener and be shutdown after yours is.

Shiri answered 1/6, 2016 at 1:28 Comment(1)
I am running in a Servlet 3.0 container and haven't done any manual configuration of Log4j's servlet components.That

© 2022 - 2024 — McMap. All rights reserved.