log4j,slf4j,logback简单介绍见 LogBack简易教程
Logback浅析
简单的将,slf4j是一个日志的框架,有各种日志的接口,但是并不包含实际的写日志的方法。
log4j,logback则各自独立的实现了日志的写入。
1.使用log4j独立生成日志
项目中导入log4j.jar,log4j.properties或log4j.xml
package com.spike.test; import java.io.IOException; import java.sql.SQLException; import org.apache.log4j.Logger; public class Log4jExample { static Logger log = Logger.getLogger(Log4jExample.class.getName()); public static void main(String[] args)throws IOException,SQLException{ log.debug("Debug"); log.info("Info"); log.error("error"); System.out.println(Log4jExample.class.getName()+" test"); } }
输出结果如下,日志写入到log4j配置文件指定的文件中
[03 14:04:02,721 DEBUG] [main] test.Log4jExample - Debug [03 14:04:02,723 INFO ] [main] test.Log4jExample - Info [03 14:04:02,723 ERROR] [main] test.Log4jExample - error com.spike.test.Log4jExample test
2.slf4j + log4j
项目中包含slf4j-api.jar,log4j.jar,slf4j-log4j.jar,以及log4j日志的配置文件
package com.spike.test; import java.io.IOException; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Slf4jExample { /* Get actual class name to be printed on */ static Logger log = LoggerFactory.getLogger(Slf4jExample.class.getName()); public static void main(String[] args)throws IOException,SQLException{ log.debug("Debug"); log.info("Info"); log.error("error"); System.out.println(Slf4jExample.class.getName()+" test"); } }
输出结果如下,日志写入到log4j配置文件指定的文件
[03 14:07:50,548 DEBUG] [main] test.Slf4jExample - Debug [03 14:07:50,549 INFO ] [main] test.Slf4jExample - Info [03 14:07:50,549 ERROR] [main] test.Slf4jExample - error com.spike.test.Slf4jExample test
3.slf4j + logback
项目中导入slf4j-api.jar,logback-access.jar,logback-classic.jar,logback-core-1.1.7.jar,以及logback.xml配置文件
package com.spike.test; import java.io.IOException; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogbackExample { static Logger log = LoggerFactory.getLogger(Log4jExample.class.getName()); public static void main(String[] args)throws IOException,SQLException{ log.debug("Debug"); log.info("Info"); log.error("error"); System.out.println(Log4jExample.class.getName()+" test"); } }
输出结果如下,日志写入到logback.xml指定的文件中
2016-11-03 14:14:31,799 [DEBUG] [main] com.spike.test.Log4jExample [LogbackExample.java : 18] Debug 2016-11-03 14:14:31,803 [INFO] [main] com.spike.test.Log4jExample [LogbackExample.java : 19] Info 2016-11-03 14:14:31,803 [ERROR] [main] com.spike.test.Log4jExample [LogbackExample.java : 20] error com.spike.test.Log4jExample test
参考