在spring-web项目中,log4j的配置位于log4j.properties文件中,其中日志路径使用环境变量配置(配置在/etc/profile)。但是,实际运行该路径没有生效。如果直接写路径,是没有问题的。
log4j.appender.logFile.File = ${BYTREES_LOG4J_FILE}
原因分析:
log4j采用System.getProperty读取系统属性,而System.getenv才是读取环境变量,可以参考org.apache.log4j.helpers.OptionConverter
解决方案:
创建一个Listener,在spring启动前,把需要将环境变量,转化成系统属性。
Listener创建:
package com.bytrees.utils;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Log4jListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
String log4jLogFile = System.getenv("BYTREES_LOG4J_FILE");
if (log4jLogFile != null) {
System.setProperty("BYTREES_LOG4J_FILE", log4jLogFile);
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.getProperties().remove("BYTREES_LOG4J_FILE");
}
}
配置web.xml,注意这个必须在ContextLoaderListener之前
<listener>
<listener-class>com.bytrees.utils.Log4jListener</listener-class>
</listener>