【发布时间】:2013-03-11 21:02:07
【问题描述】:
我正在使用传统方式加载 log4j.xml
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:conf/log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
这很好用,但现在我需要根据我所在的环境加载不同的 log4j.xml 文件只需将其更改为
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:conf/log4j-${ENV-NAME}.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
并且 spring 将在每个环境中加载正确的 log4j 文件,但这可能不起作用,因为 web.xml 在 spring 之前加载。我遇到了这种方法
<bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
<property name="targetMethod" value="initLogging" />
<property name="arguments">
<list>
<value>log4j-${ENV-NAME}.xml</value>
</list>
</property>
</bean>
所以本质上是将 log4j 的配置移动到 spring 上下文文件而不是 web.xml 中。但这也不起作用,因为某种原因,日志记录是以记录所有内容的方式启用的。那么如何根据环境变量使用不同的 log4j.xml 文件或在 servletcontextlistener 中以编程方式加载它。
【问题讨论】:
-
你也在用maven吗?
-
@Jintian DENG 是的,我是
-
那我建议使用maven配置文件。看看这个:stackoverflow.com/questions/9543219/…
-
我刚刚以编程方式配置它 public void contextInitialized(ServletContextEvent sce) { String env = ResourceUtils.getEnvironment(); //为此环境加载log4j配置文件 String log4jFile = "/WEB-INF/classes/conf/log4j-" + env.toLowerCase() + ".xml"; DOMConfigurator.configure(sce.getServletContext().getRealPath(log4jFile));