什么是使用Java Config但不使用web.xml在Spring MVC Webapp中为log4j2提供初始化的正确方法? [英] What is right way to supply initialization for log4j2 in a Spring MVC Webapp using Java Config and no web.xml?

查看:288
本文介绍了什么是使用Java Config但不使用web.xml在Spring MVC Webapp中为log4j2提供初始化的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Spring MVC Web App (4.0) with log4j2. This webapp uses no web.xml and takes care of configuration through Java Config. Log4j2 configuration needs to take place in an external config file, not on the classpath.

在先前使用web.xml的化身中,

In a previous incarnation with web.xml we had

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

这可行.

在没有web.xml的新世界中,我尝试了以下方法:

In the new web.xml-less world, I tried this:

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

这不起作用.这似乎为时已晚,无论如何都行不通.日志显示:

This does not work. It seems to happen too late and in any event doesn't work. The logs show:

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

并且没有log4j日志记录发生.

and no log4j logging occurs.

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

What is the right way to replace this context-param declaration with web.xml in a web.xml-less Spring MVC app?

更新:

我可以通过添加以下web.xml来解决此问题:

I can make this problem go away by adding the following 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>

当然,必须有更好的方法!

Surely, there must be a better way!

推荐答案

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

I believe you can reconfigure log4j2 to a new config file during runtime like this.

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

只需将其添加到您的onStartup中即可.

Could just add this to your onStartup.

这篇关于什么是使用Java Config但不使用web.xml在Spring MVC Webapp中为log4j2提供初始化的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆