log4j 一直有個問題沒法知足我,有可能我還不知道怎麼去使用它。數據庫
就是他會把項目中全部的日誌信息都記到一個文件裏面,而業務系統每每須要根據某個業務流程查看日誌分析。ide
public class BusinessLogUtil { public enum Level { ERROR(40, "ERROR"), WARN(30, "WARN"), INFO(20, "INFO"), DEBUG(10, "DEBUG"), TRACE(0, "TRACE"); private int levelInt; private String levelStr; private Level(int i, String s) { this.levelInt = i; this.levelStr = s; } public int toInt() { return this.levelInt; } @Override public String toString() { return this.levelStr; } } /** * 獲得記錄日誌全部的文件:行號 * * @return */ private static String getLineInfo() { StackTraceElement ste = new Throwable().getStackTrace()[3]; return MessageFormat.format("[{0}:{1}]", ste.getClassName(), ste.getLineNumber()); } /** * 記錄日誌信息 * * @param businessName * @param content */ private void write(String businessName, Level logLevel, String content) { String logKey = businessName; if (logKey.contains("_")) { logKey = logKey.split("_")[0]; } boolean isContinue = true; //TODO 此處根據 businessName 去數據庫裏面看這個業務日誌有沒有要求開啓 if (!isContinue) { //若是Elb_Settings 沒開啓開關,則不記錄日誌 return; } FileOutputStream out = null; BufferedOutputStream Buff = null; try { Date currentDate = new Date(); String logRoot = System.getProperty("catalina.home"); if (StringUtil.isNullOrEmpty(logRoot)) { logRoot = ""; } String fileName = logRoot + "/logs/" + businessName + "_" + logLevel.levelStr.toLowerCase() + "." + com.iron.fast.util.DateUtil.toFormatString("yyyy-MM-dd", currentDate) + ".log"; out = new FileOutputStream(fileName, true); Buff = new BufferedOutputStream(out); String msg = MessageFormat.format("{0} {1} {2} - {3}\r\n", DateUtil.toFormatString("yyyy-MM-dd HH:mm:ss", currentDate), logLevel.levelStr, getLineInfo(), content); Buff.write(msg.getBytes("utf-8")); Buff.flush(); Buff.close(); } catch (Exception var15) { var15.printStackTrace(); } finally { try { Buff.close(); out.close(); } catch (Exception var14) { var14.printStackTrace(); } } } /** * 業務日誌 * * @param businessName * @param content */ public void info(String businessName, String content) { write(businessName, Level.INFO, content); } /** * 警告日誌,同時也會記錄到 info 中 * * @param businessName * @param content */ public void warn(String businessName, String content) { write(businessName, Level.WARN, content); write(businessName, Level.WARN, content); } /** * 錯誤日誌,同時也會記錄到 info 中,warn 中不記 * * @param businessName * @param content */ public void error(String businessName, String content) { write(businessName, Level.ERROR, content); write(businessName, Level.ERROR, content); } }