項目開發中常常會有這種狀況,項目成員電腦開發系統有window、mac,而線上發佈是liunx。java
這種狀況下就會有問題,不方便協同,而且每次發佈都要修改設置,這樣會很麻煩,若是忘記了,把本地配置更新至線上後還會出現不能正常記錄日誌的問題,確實是個麻煩事。web
爲了解決問題,實現方案就是在項目啓動初始化時自動進行操做系統判斷針對不一樣系統進行統一輸出路徑設置,以達到協同目的。apache
廢話很少說,上實例。app
1、初始化項目log4j保存路徑ide
一、設置log4j輸出目錄至環境變量ui
public class Log4jPathListener implements ServletContextListener{ final static String LOG4J_PATH = "log4j.path"; @Override public void contextInitialized(ServletContextEvent sce) { String projectName = sce.getServletContext().getInitParameter("log4j.filename"); if(projectName == null || "".equals(projectName.trim())){ System.err.println("警告: Log4jListener init log4j path fail! The parameter 'log4j.filename' is not configured in web.xml."); return; } System.setProperty(LOG4J_PATH, LogUtil.getSavePath(projectName)); } @Override public void contextDestroyed(ServletContextEvent sce) { System.getProperties().remove(LOG4J_PATH); } }
二、根據操做系統判判定義固定輸出路徑操作系統
public static String getSavePath(String projectName){ if (StringUtil.isEmpty(projectName)) { System.err.println("Warn: save log4j log path value 'projectName' is null!!! "); } String path = ""; if(SystemUtils.IS_OS_WINDOWS){ path = "D:\\logs\\"+projectName+"\\"; }else if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) { path = "/Users/Documents/log/"+projectName+"/"; }else{ path = "/data/project_logs/"+projectName+"/"; } return path; }
2、web.xml 監聽器 配置日誌
<!-- 設置log4j文件保存路徑 --> <listener> <listener-class>com.showlike.core.listener.Log4jPathListener</listener-class> </listener> <context-param> <param-name>log4j.filename</param-name> <param-value>test</param-value> </context-param>
3、log4j配置文件動態輸出路徑修改[${log4j.path}代替原有固定輸出目錄]code
log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender log4j.appender.A1.File=${log4j.path}DruidInfoSql.log log4j.appender.A1.DatePattern='.'yyyy-MM-dd log4j.appender.A1.ImmediateFlush=true log4j.appender.A1.Append=true log4j.appender.A1.Threshold=info log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] [%p] [%c] - %m%n log4j.additivity.A1=false
END。。。xml