在Spring MVC web应用程序中,使用Java Config而不使用web.xml为log4j2提供初始化的正确



我有一个带有log4j2的Spring MVC Web应用程序(4.0(。此web应用程序不使用web.xml,而是通过Java Config进行配置Log4j2配置需要在外部配置文件中进行,而不是在类路径中

在web.xml的前一个版本中,我们有

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

这起到了作用。

在新的无网络的世界里,我尝试了这个:

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");

这不起作用。这似乎发生得太晚了,而且无论如何都不起作用。日志显示:

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

并且不发生log4j日志记录。

在没有web.xml的Spring MVC应用程序中,用web.xml替换此上下文参数声明的正确方法是什么?

更新:

我可以通过添加以下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>

当然,一定有更好的办法!

我相信您可以像这样在运行时将log4j2重新配置为一个新的配置文件。

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

可以将此添加到您的onStartup中。

这可能有点太晚了,但您可以执行以下操作将log4j2配置设置为外部路径:

public class ApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext)
        throws ServletException {
        servletContext.setInitParameter(Log4jWebSupport.LOG4J_CONFIG_LOCATION, "file:///path/to/log4j2.xml");

我还没有测试过它,但以下内容值得一试;将onStartup(…)方法中的servletContext.setAttribute(…)调用替换为以下Log4jConfigurer调用:

Log4jConfigurer.initLogging("file:///path/to/log4j2.xml")

当您在web.xml文件的<context-param>中使用log4jConfigLocation时,基本上就是这样(通过Log4jWebConfigurer,请参阅代码(。

我只是想知道这是否也适用于log4j2,尽管我也不希望使用<context-param>的方式。当您还在使用web.xml文件时,是否也使用了log4j2?

最新更新