javase 配置log4j 不用級別的日誌輸出到不同的檔案
阿新 • • 發佈:2021-02-01
1 配置 log4j.properties配置檔案,路徑和配置如下:
### 設定### log4j.rootLogger = debug,stdout,D,I,W,E ### 輸出資訊到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n ### 輸出DEBUG 級別的日誌 ### #log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D = com.jack.utils.MyAppender log4j.appender.D.File = ./logs/debug.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.append=false log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 輸出WARN 級別的日誌 ### #log4j.appender.I = org.apache.log4j.DailyRollingFileAppender log4j.appender.I = com.jack.utils.MyAppender log4j.appender.I.File =./logs/info.log log4j.appender.I.Append = true log4j.appender.I.Threshold = INFO log4j.appender.I.append=false log4j.appender.I.layout = org.apache.log4j.PatternLayout log4j.appender.I.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 輸出WARN 級別的日誌 ### #log4j.appender.W = org.apache.log4j.DailyRollingFileAppender log4j.appender.W = com.jack.utils.MyAppender log4j.appender.W.File =./logs/warn.log log4j.appender.W.Append = true log4j.appender.W.Threshold = WARN log4j.appender.W.append=false log4j.appender.W.layout = org.apache.log4j.PatternLayout log4j.appender.W.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 輸出ERROR 級別的日誌 #log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E = com.jack.utils.MyAppender log4j.appender.E.File =./logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.append=false log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
2 測試程式碼,如下:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private final static Logger logger = LoggerFactory.getLogger(App.class); public static void main(String[] args) { logger.debug("log debug ... "); logger.info("log info ... "); logger.warn("log warn ... "); logger.error("log error ... "); } }
3 實際效果,如下:
4 關鍵配置
log4j.appender.D = com.jack.utils.MyAppender
log4j.appender.I = com.jack.utils.MyAppender
log4j.appender.W = com.jack.utils.MyAppender
log4j.appender.E = com.jack.utils.MyAppender
5 重寫了原生的 org.apache.log4j.DailyRollingFileAppender
重寫後的程式碼如下:
import org.apache.log4j.DailyRollingFileAppender; import org.apache.log4j.Priority; /** * @desc: * @since Apr 17, 2013 * @author chaisson * * <p> */ public class MyAppender extends DailyRollingFileAppender { @Override public boolean isAsSevereAsThreshold(Priority priority) { //只判斷是否相等,而不判斷優先順序 return this.getThreshold().equals(priority); } }