關於LOG4J 按照級別輸出日誌,並按照級別輸出到不一樣文件中的說法有不少, 網上貼的最多的log4j.properties的設置是這樣的java
- log4j.rootLogger=info,stdout,info,debug,error
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
-
- log4j.logger.info=info
- log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
- log4j.appender.info.layout=org.apache.log4j.PatternLayout
- log4j.appender.info.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
- log4j.appender.info.datePattern='.'yyyy-MM-dd
- log4j.appender.info.Threshold = INFO
- log4j.appender.info.append=true
- log4j.appender.info.File=${webApp.root}/WEB-INF/logs/info.log
-
- log4j.logger.debug=debug
- log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
- log4j.appender.debug.layout=org.apache.log4j.PatternLayout
- log4j.appender.debug.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
- log4j.appender.debug.datePattern='.'yyyy-MM-dd
- log4j.appender.debug.Threshold = DEBUG
- log4j.appender.debug.append=true
- log4j.appender.debug.File=${webApp.root}/WEB-INF/logs/debug.log
-
- log4j.logger.error=error
- log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
- log4j.appender.error.layout=org.apache.log4j.PatternLayout
- log4j.appender.error.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
- log4j.appender.error.datePattern='.'yyyy-MM-dd
- log4j.appender.error.Threshold = ERROR
- log4j.appender.error.append=true
- log4j.appender.error.File=${webApp.root}/WEB-INF/logs/error.log
而實際上這部分代碼解決不了按照LOG4J的級別文件進行文件輸出。web
配置中關鍵的配置說明是這一句:apache
- log4j.appender.debug.Threshold = INFO
而它的做用是輸出INFO級別以上的內容到${webApp.root}/WEB-INF/logs/info.log中,因此info.log文件中包含了ERROR級別的文件。app
正確的解法是:ide
定義本身的Appender類,繼承DailyRollingFileAppender,改寫針對Threshold 的設置說明。oop
源代碼記載:this
- public boolean isAsSevereAsThreshold(Priority priority)
- {
- return threshold == null || priority.isGreaterOrEqual(threshold);
- }
重寫 isAsSevereAsThreshold(Priority priority)方法url
- public class LogAppender extends DailyRollingFileAppender {
-
- @Override
- public boolean isAsSevereAsThreshold(Priority priority) {
-
- return this.getThreshold().equals(priority);
- }
- }
這樣,進行惟一判斷,只有當Threshold與priority一致時,才進行輸出,就實現了真正Log4j按照級別輸出日誌文件。spa
在log4j.properties中,將配置文件做以下修改:.net
- log4j.logger.info=info
- <span style="BACKGROUND-COLOR: #33cc00">log4j.appender.info=com.company.LogAppender
- </span>log4j.appender.info.layout=org.apache.log4j.PatternLayout
- log4j.appender.info.layout.ConversionPattern=[%-5p] [%d{HH:mm:ss}] %c - %m%n
- log4j.appender.info.datePattern='.'yyyy-MM-dd
- log4j.appender.info.Threshold = INFO
- log4j.appender.info.append=true
- log4j.appender.info.File=${webApp.root}/WEB-INF/logs/info.log
到此,即完成了按照Log4j按照日誌級別輸出到不一樣文件中的功能。