標籤:des style blog http color os io java ar
如何在系統啟動的時候載入log4j的設定檔呢?
1、自訂監聽類並且繼承“ServletContextListener”介面:
1 package cn.ibeans.common; 2 3 import java.io.File; 4 import java.util.List; 5 6 import javax.servlet.ServletContextEvent; 7 import javax.servlet.ServletContextListener; 8 9 import org.apache.log4j.Logger;10 import org.apache.log4j.PropertyConfigurator;11 import cn.ibeans.common.util.FileUtil;12 /**13 * 14 * @author hezuoan15 *16 */17 public class ApplicationListener implements ServletContextListener {18 19 private static Logger log = Logger.getLogger(ApplicationListener.class);20 @Override21 public void contextInitialized(ServletContextEvent sce) {22 23 //擷取log4j設定檔的地址24 String log4jPath = ApplicationDispatchServlet.class.getResource("/").getPath() + "config/logs";25 List<File> files = FileUtil.listFile(new File(log4jPath), "properties", false);26 27 if ((files == null) || (files.size() == 0)){28 log.info("沒有發現Log4j設定檔.");29 return;30 }31 for (File file : files) {32 //載入設定檔33 PropertyConfigurator.configure(file.getPath());34 }35 log.info("載入Log4j設定檔完成.");36 }37 38 @Override39 public void contextDestroyed(ServletContextEvent sce) { }40 41 }
上述代碼中FileUtil.listFile() 方法是自己封裝的工具類。
1 /** 2 * 擷取檔案夾下的所有檔案 3 * @param dir 檔案夾路徑 4 * @param filename 尾碼名稱 5 * @param recursive 是否遞迴該檔案夾下的子檔案夾 6 * @return 7 */ 8 public static List<File> listFile(File dir,final String filename, boolean recursive) 9 {10 if (!dir.exists()) {11 throw new IllegalArgumentException("目錄:" + dir + "不存在");12 }13 if (!dir.isDirectory()) {14 throw new IllegalArgumentException(dir + "不是目錄");15 }16 FileFilter ff = null;17 if ((filename == null) || (filename.length() == 0)) {18 ff = new FileFilter()19 {20 public boolean accept(File pathname)21 {22 return true;23 }24 };25 } else {26 ff = new FileFilter()27 {28 public boolean accept(File pathname)29 {30 if (pathname.isDirectory()) {31 return true;32 }33 String name = pathname.getName();34 if (name.indexOf(filename) != -1) {35 return true;36 }37 return false;38 }39 };40 }41 return listFile(dir, ff, recursive);42 }43 44 private static List<File> listFile(File dir, FileFilter ff, boolean recursive)45 {46 List<File> list = new ArrayList<File>();47 File[] subs = dir.listFiles(ff);48 if ((subs != null) && (subs.length > 0)) {49 for (File sub : subs) {50 if (sub.isFile()) {51 list.add(sub);52 } else if (recursive) {53 list.addAll(listFile(sub, ff, true));54 }55 }56 }57 return list;58 }View Code
2、在Web.xml 添加該監聽器的配置:
<listener> <listener-class>cn.ibeans.common.ApplicationListener</listener-class> </listener>
載入log4j的設定檔的目的是為了使記錄檔“放在跟工程相對路徑的地方”,這樣即使將項目移植到不同的作業系統上面,顯示也是正常的。
WEB系統啟動時載入Log4j的設定檔