使用 ServletContextListener 和 SLF4J 在 contextDestroyed 上没有日志输出

No log output on contextDestroyed using ServletContextListener & SLF4J

我正在尝试将 (Vaadin) servlet 已停止的消息写入记录器,这使用 SLF4J 和 Log4j2。

为此,我使用了 ServletContextListener,它会在应用程序启动时记录一条消息。但是,在 contextDestroyed 方法中登录时,我无法获得任何输出...这是我的实现:

@WebListener
public class VaadinLogger implements ServletContextListener {

    private static final Logger logger = LoggerFactory.getLogger(VaadinLogger.class);

    @Override
    public void contextInitialized(ServletContextEvent contextEvent) {
        // Remove appenders from JUL loggers
        SLF4JBridgeHandler.removeHandlersForRootLogger();

        // Install bridge
        SLF4JBridgeHandler.install();

        // Get servlet context
        ServletContext context = contextEvent.getServletContext();

        // Retrieve name
        String name = context.getServletContextName();

        // Log servlet init information
        logger.info("Start \"{}\"", name);
    }

    @Override
    public void contextDestroyed(ServletContextEvent contextEvent) {
        // Get servlet context
        ServletContext context = contextEvent.getServletContext();

        // Retrieve name
        String name = context.getServletContextName();

        // Log servlet destroy information
        logger.info("End \"{}\"{}", name, System.lineSeparator()));

        // Uninstall bridge
        SLF4JBridgeHandler.uninstall();
    }
}

此时,我猜这可能是因为在调用 contextDestroyed 时,不再可能进行日志记录,因为它们已经被垃圾收集器销毁了。

所以现在我的问题是,是否可以在销毁上下文之前记录 servlet 已停止,或者让上下文监听器在销毁 log4j2 记录器之前执行?

提前致谢!

首先,您的类路径中是否有 log4j 2.x api、核心和网络 jar? log4j-web-2.x.jar 还注册了一个上下文侦听器,用于在卸载 Web 应用程序时关闭日志记录子系统。

如果您的侦听器在此之后运行,您将无法再记录任何内容。

您可以通过在 log4j2 配置文件中设置 <Configuration status="trace" ... 来检查发生了什么。

log4j2 (log4j-web-xx.jar) 带有一个网络片段。此片段包含一个 ServletContextListener。监听器的顺序取决于初始化(参见 Servlet Specification)。默认值:首先是您的应用程序,然后是其他应用程序。

您可以更改顺序以在 web.xml 中指定 <absolut-ordering>:

<web-app>
  <absolute-ordering>
    <name>log4j</name>
    <others/>
  </absolute-ordering>

另请参阅:servlet-30-web-fragmentxml

从 log4j 2.14.1 开始,您可以禁用自动关闭并添加一个侦听器来停止记录器。

<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>
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>