特定于环境的log4j配置由spring

ade*_*ood 18 spring log4j

我正在使用传统方式加载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>
Run Code Online (Sandbox Code Playgroud)

这工作正常,但现在我需要根据环境变量/ jndi条目定义的环境加载不同的log4j.xml文件.所以我希望通过新的Spring 3.1属性管理我可以改变这个至

<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>
Run Code Online (Sandbox Code Playgroud)

和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>
Run Code Online (Sandbox Code Playgroud)

所以基本上将log4j的配置移动到spring上下文文件而不是web.xml.但是,由于某种原因,日志记录以一切都记录的方式启用,因此无法正常工作.那么如何基于环境变量使用不同的log4j.xml文件或者在servletcontextlistener中以编程方式加载它.

Pat*_*a K 18

帮助adeelmahmood已经太晚了,但希望其他人能从我的回答中受益.事情是adeelmahmood是对的,这个配置:

<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>
Run Code Online (Sandbox Code Playgroud)

工作正常,但是:

  • Log4jConfigListener应该在web.xml中的ContextLoaderListener之前注册!!!
  • 您还必须记住Log4jConfigListener假定扩展的WAR文件.

然后,如果设置了ENV-NAME环境变量,它将按预期工作.

顺便说一下,$ {ENV-NAME}也可以用在spring配置文件中!这不是一切......您也可以使用我们的env.property设置弹簧配置文件:

<context-param>
 <param-name>spring.profiles.active</param-name>
 <param-value>${ENV-NAME}</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

这样你就可以设置log4jConfigLocation和spring profile,两者都有一个相同的env.变量.

顺便说一句,以防万一:使用Maven配置文件为开发,测试和生产分别构建不是好习惯.阅读例如.http://java.dzone.com/articles/maven-profile-best-practices并记住:"使用配置文件来管理构建时变量,而不是运行时变量,而不是(使用RARE例外)工件的替代版本" .

  • 感谢您回来执行此操作,只给了我在我的应用程序中使用此功能所需的信息。 (2认同)