日志简单介绍
当在项目的编写中,我们使用最多的是使用输入输出语句,可以输出程序运行的进度,也间接的推断出BUG的大致位置。当代码比较多的时候,则需要添加过多的输出语句,同时对于调试比较麻烦。因此引入日志,可以记录程序在运行状态,并进行控制台输出或者存储在特定文件中。
日志的介绍
日志门面
一组使用facade设计模式设计的一组接口应用;日志门面有:Jcl(commons-loggings),Slf4j(simple logging facade for java)。
日志实现
即接口的实现。日志的实现有:Log4j,Log4j2,Logback,JUL.
日志的使用
对于编码来说,系统会直接与接口层交互,建议面向接口编程,因为如果直接使用具体的日志实现代码进行编程,对于后期选择其他日志框架时,需要修改很多地方。
对于不同的日志,为了实现统一的使用,提供了相应的适配器来进行不同日志之间的兼容。
例如:
其中Adaptation layer是bridge层。为什么需要bridge?其实slf4j(slf4j-api.jar)只提供了一个门面,并没有具体的实现。像最左边的那一列,如果我们的系统中只引入了slf4j-api.jar,那么日志无法输出。
问题
注意Slf4J不能单独使用,因为他只是一个接口,需要配合相应的日志实现才可以使用。
常见错误:
SLF4J: No SLF4J providers were found. SLF4J:Defaulting to no-operation (NOP) logger implementation
分析:
缺少实现类,一般情况下,需要使用接口+适配+日志实现,eg: slf4j-api-xx.jar + slf4j-log4j + log4j.有的不用中间层。
例如:以第三列为例
slf4j-api-1.8.0-beta0.jar slf4j-log4j12-1.8.0-beta0.jar log4j-1.2.17.jar
或者:第五列为例
slf4j-api-1.8.0-beta0.jar slf4j-simple-1.8.0-beta0.jar
其中抽象层和中间层的版本号是一致的.
具体案例:
1.创建项目
2.导入Jar包
slf4j-api-1.8.0-beta4.jar slf4j-log4j12-1.8.0-beta0.jar log4j-1.2.17.jar
3.在src下创建日志配置文件 log4j.properties
log4j.rootLogger=info, stdout //级别 log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n //格式
4.编写代码
test类
package com.dong.logback_helloworld;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class test {
final static Logger logger = LoggerFactory.getLogger(test.class);
public static void main(String[] args) {
logger.info("enter the test class");
other ot = new other();
ot.otherMethod(20);
logger.info("exit hte test class");
}
}
other类
package com.dong.logback_helloworld;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class other {
public final static Logger logger = LoggerFactory.getLogger(other.class);
public void otherMethod(int i){
logger.info("enter the new class other.class otherMethod function");
if(i % 2 == 0 ){
logger.info("i is old ");
}else{
logger.info("i is don't old");
}
logger.info("exit the new class other.class otherMethod function");
}
}
5.运行程序
E:\Java8\bin\java.exe......
2019-06-26 21:59:11,924 INFO [com.dong.logback_helloworld.test] - enter the test class
2019-06-26 21:59:11,942 INFO [com.dong.logback_helloworld.other] - enter the new class other.class otherMethod function
2019-06-26 21:59:11,942 INFO [com.dong.logback_helloworld.other] - i is old
2019-06-26 21:59:11,942 INFO [com.dong.logback_helloworld.other] - exit the new class other.class otherMethod function
2019-06-26 21:59:11,942 INFO [com.dong.logback_helloworld.test] - exit hte test class
Process finished with exit code 0
如有错误,敬请指出,与君共勉;