我正在使用传统的方式加载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文件,该文件由环境变量/jndi条目定义。因此,我希望在新的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>
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中呢?
发布于 2016-12-27 21:20:24
这可能对最近的读者也有帮助:在Log4j 2.7 (但它可能更旧)中,参数名称已被更改:请参阅接口Log4jWebSupport
:
/**
* The {@link javax.servlet.ServletContext} parameter name for the location of the configuration.
*/
String LOG4J_CONFIG_LOCATION = "log4jConfiguration";
发布于 2021-12-20 07:00:54
默认情况下,Spring Boot从系统的默认位置(比如Logback的classpath:logback.xml
)获取本机配置,但是您可以使用logging.config
属性设置配置文件的位置。
logging.config=classpath:log4j-<ENV-NAME>.xml
https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/html/howto-logging.html
https://stackoverflow.com/questions/15348550
复制相似问题