1. 程式人生 > >spring+log4j配置檔案無法讀取環境變數問題

spring+log4j配置檔案無法讀取環境變數問題

在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 PropertiesListener 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.PropertiesListener</listener-class>  
</listener>