slf4j-api、slf4j-log4j12以及log4j之间的关系 :[url]http://blog.csdn.net/woshixuye/article/details/20858239[/url]
使用slf4j + Log4j2构建日志 :[url]http://blog.csdn.net/heyutao007/article/details/50371668[/url]
首先下载相关jar,log4j-1.2.17.jar,slf4j-api-1.7.9.jar,slf4j-log4j12-1.7.9.jar
package org;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class testSFL4J {
private static Logger log = LoggerFactory.getLogger(testSFL4J.class);
public static void main(String[] args) {
log.debug("=======test root=========");
log.info("========test daily level info=========");
log.warn("========test warn=========");
log.error("========test error=========");
}
}
log4j有两种配置方式,一种为XML,一种为java属性文件properties,我的配置方式为
log4j.properties,具体内容如下:
log4j.rootLogger = DEBUG,stdout,D
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Threshold = DEBUG
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} %c %l %m%n
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} %c %m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = F://logs/log.log
log4j.appender.D.Append = true
### when the appender Threshold is null, extend from rootLogger,
### when the appender Threshold is exist, compare the Threshold with the level of rootLogger
### set the higher level
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [%-5p] %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - %c%m%n
#log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.E.File =F://logs/error.log
#log4j.appender.E.Append = true
#log4j.appender.E.Threshold = ERROR
#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
控制台输出:
[DEBUG] 2016-10-22 11:52:52,084 org.testSFL4J =======test root=========
[INFO ] 2016-10-22 11:52:52,084 org.testSFL4J ========test daily level info=========
[WARN ] 2016-10-22 11:52:52,084 org.testSFL4J ========test warn=========
[ERROR] 2016-10-22 11:52:52,084 org.testSFL4J ========test error=========
文件输出:
[ERROR] 2016-10-22 11:52:52 [ main:0 ] - org.testSFL4J========test error=========
总结:
[color=blue]从上面可以看出,当appender的Threshold为控制,则继承rootLogger,当不为null时,输出等级,以appender和rootLogger等级高的为准。[/color]