SLF4J(SLF4J)

创建Maven项目导入依赖

<dependencies><!–SLF4J核心依赖–>    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-api</artifactId>        <version>1.7.30</version>    </dependency>    <!–SKF4J自带的简单日志实现–>    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-simple</artifactId>        <version>1.7.32</version>    </dependency>

<dependency>    <groupId>junit</groupId>    <artifactId>junit</artifactId>    <version>4.12</version>    <scope>test</scope></dependency>

</dependencies>

<build>    <plugins>        <!–设置编译版本为1.8–>        <plugin>            <groupId>org.apache.maven.plugins</groupId>            <artifactId>maven-compiler-plugin</artifactId>            <version>3.8.1</version>            <configuration>                <source>1.8</source>                <target>1.8</target>                <encoding>UTF-8</encoding>            </configuration>        </plugin>    </plugins></build>

入门案列:slf4j-simple

@Testpublic void test01(){/** 入门案例* SLF4J对日志级别的划分* trace,debug,info,warn,error五个级别* tarce:日志的追踪信息* debug:日志的详细信息* info:日志的关键信息* warn:日志的警告信息* error:日志的错误信息* 在没有任何其他日志实现框架基础的基础之上* slf4j使用的是自带的框架slf4j-simple* slf4j使用的就是自带的框架slf4j-simple* slf4j-simple也可以单独以来的形式导入进来* */    Logger logger = LoggerFactory.getLogger(SKF4JTest.class);    logger.trace(“trace信息);    logger.debug(“debug信息);    logger.info(“info信息);    logger.warn(“warn信息);    logger.error(“error信息);}

SLF4J动态打印异常信息

@Testpublic void test02(){/** 我们输出动态的信息时* 也可以使用占位符的形式来代替字符串的拼接** 我们有时候输出的日志信息/,需要我们搭配动态的数据* 有可能是信息,有可能是数据库中的数据* 总之我们这样做的最大好处就是可以让日志答应更加灵活* 若果是通过字符串拼接的形式,不只是麻烦,而且更重要的是可读性查* 我们的日志打印是支持替代符的形式做日志的拼接的* 一般情况下,几乎所有的日志实现产品,都会提供这种基础功能** */    Logger logger = LoggerFactory.getLogger(SKF4JTest.class);String name=“zs”;int age=23;logger.info(学生信息姓名:”+name+年龄:”+age);logger.info(学生信息姓名:{},年龄:{}”,new Object[]{name,age});logger.info(学生信息姓名:{},年龄:{}”,name,age);}

打印异常信息

@Test    public void test03(){        /*        * 日志对异常信息的处理        * 一般情况下,我们在开发中的异常信息,那都是记录在控制台中的(我们在开发环境中的一种打印方式)        * 我们会根据异常信息提供有用的线索调式bug        * 但是在真实生产环境中(项目上线),对于服务器或者是系统相关的问题        * 在控制台上也会提供相应的异常或错误信息的输出        * 但是在这种错误输出方式(输出的时间,位置,格式。。。。。)都是服务器系统默认的        * 我们可以通过日志技术,选择将异常以日志的方式,进行输出查看        * 输出的时间,位置(控制台,文件),格式完全由我们自己定义        * *///        System.out.println(123);        Logger logger = LoggerFactory.getLogger(SKF4JTest.class);        try {            Class.forName(“aaa”);        } catch (ClassNotFoundException e) {            //打印栈追踪信息           // e.printStackTrace();            logger.info(“xxx类中的xxx方法出现了异常,请及时关注信息);            //e是应用类型对象,不能根前面的{}做有效的字符串拼接            //logger.info(“具体错误是:{}”,e);            //我们不用加{},直接后面加上异常对象即可            logger.info(具体错误是:”,e);        }    }

试着将SLF4J同时集成多个日志实现的结果分析

引入依赖

<!–logback的依赖–>    <dependency>        <groupId>ch.qos.logback</groupId>        <artifactId>logback-classic</artifactId>        <version>1.2.3</version>    </dependency>

使用:

@Testpublic void test04(){    /*    * 集成其他日志之前    * 观察官网图    * SLF4J日志门面,共有3种对日志实现绑定    * 1.在没有绑定任何日志的基础上,日志是不能绑定实现任何功能的    * 值得大家注意的是,通过我们刚刚演示的案列slfj-simple是slf4j官网提供的    * 使用的时候也需要导入依赖,slf4j核心依赖是不提供任何实现的    * 2.logback和simple(包括nop)    * 都是slf4j门面时间线后面提供的日志实现,所以API完全遵循slf4j进行的设计    * 那么我们只需要导入想要使用的日志实现依赖,即可与SLF4J无缝衔接    * 值得一提的是nop虽然也划分到实现中了,但是他是指不时现日志记录(后续回提到)    * 3.log4j和JUL    * 都是slf4j的门面时间线前面的日志实现,所以API不遵循slf4j进行设计    * 通过适配桥接的技术完成与日志门面的衔接    *    * 将logback框架集成进来    *    * 测试1:    * 在原有的SLF4J=Simple日志实现的基础上,又集成了lombok    * 通过这次的测试,日志打印出来java.lang.ClassNotFoundException: aaa    * 通过这一句发现SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]    * 虽然集成了lombok,但是我们现在使用的仍然是slf4j-simple    * 事实上只要出现了这个提示SLF4J: Class path contains multiple SLF4J bindings.    * 在SLF4J环境下证明同时出现了多个日志实现    * 如果pom.xml文件上第一个是logback则使用先导入的依赖    *    *  */    Logger logger = LoggerFactory.getLogger(SKF4JTest.class);    try {        Class.forName(“aaa”);    } catch (ClassNotFoundException e) {        logger.info(具体错误是:”,e);    }}

Slf4j集成logback

测试:* 将slf4j-simple注释掉* 只留下logback那么slf4j门面使用的就是logback日志实现* 值得一提的是,这一次没有多余的提示* 所以在真实开发情况下用一种日志的集成就可以实现了** 通过这歌集成测试,我们会发现虽然底层的日志变了,但是源代码完全没有变* 这就是日志门面给我们带来最大的好处* 在底层真实记录日志的时候,不需要应用去做任何的了解* 应用只需要去记slf4j的API就可以了

————————

Create Maven project import dependency

<dependencies><!–SLF4J核心依赖–>    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-api</artifactId>        <version>1.7.30</version>    </dependency>    <!–SKF4J自带的简单日志实现–>    <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-simple</artifactId>        <version>1.7.32</version>    </dependency>

<dependency>    <groupId>junit</groupId>    <artifactId>junit</artifactId>    <version>4.12</version>    <scope>test</scope></dependency>

</dependencies>

<build>    <plugins>        <!–设置编译版本为1.8–>        <plugin>            <groupId>org.apache.maven.plugins</groupId>            <artifactId>maven-compiler-plugin</artifactId>            <version>3.8.1</version>            <configuration>                <source>1.8</source>                <target>1.8</target>                <encoding>UTF-8</encoding>            </configuration>        </plugin>    </plugins></build>

入门案列:slf4j-simple

@Testpublic void test01() {/ * * introductory case * slf4j’s classification of log levels * trace, debug, info, warn and error * start: log tracking information * debug: log details * Info: log key information * warn: log warning information * error: log error information * on the basis of no other log implementation framework * slf4j uses its own framework slf4j simple * slf4j The built-in framework slf4j simple * slf4j simple can also be imported separately * * / logger = loggerfactory getLogger(SKF4JTest.class);     logger. Trace (< strong > “trace < / strong > < strong > information < / strong > < strong >” < / strong >);     logger. Debug (< strong > “debug < / strong > < strong > information < / strong > < strong >” < / strong >);     logger. Info (< strong > “info < / strong > < strong > info < / strong >” < / strong >);     logger. Warn (< strong > “warn < / strong > < strong > information < / strong > < strong >” < / strong >);     logger. Error (< strong > “error < / strong > < strong > information < / strong > < strong >” < / strong >);}

Slf4j dynamically prints exception information

@Testpublic void test02() {/ * * when we output dynamic information, * placeholders can also be used to replace string splicing * * sometimes the log information we output / needs to be matched with dynamic data * it may be information or data in the database * in short, the greatest advantage of this is that we can make the log more flexible * if it is in the form of string splicing, it is not necessary It’s just troublesome, and more importantly, the readability check * our log printing supports log splicing in the form of substitutes * generally, almost all log implementation products provide this basic function * * * / logger = loggerfactory getLogger(SKF4JTest.class); String name=“zs”;< strong>int age=23; logger. Info (< strong > “< / strong > < strong > student information < / strong > < strong > – < / strong > < strong > name < / strong > < strong >:” < / strong > + name + < strong > “< / strong > < strong > age < / strong > < strong >:” < / strong > + age); logger. Info (< strong > “< / strong > < strong > student information < / strong > < strong > – < / strong > < strong > name < / strong > < strong >: {}, < / strong > < strong > age < / strong > < strong >: {}” < / strong >, < strong > New < / strong > Object [] {name, age}); logger. Info (< strong > “< / strong > < strong > student information < / strong > < strong > – < / strong > < strong > name < / strong > < strong >: {}, < / strong > < strong > age < / strong > < strong >: {}” < / strong >, name, age);}

Print exception information

@Test < strong > public void < / strong > test03() {/ * * log processing of exception information * generally, the exception information in our development is recorded in the console (a printing method in our development environment) * we will provide useful clues for debugging bugs based on exception information * but in the real production environment (project online), For server or system related problems * the console will also provide the output of corresponding exception or error information * but in this error output mode (output time, location, format…) All are the default of the server system * we can choose to output exceptions in the form of logs through logging technology * the output time, location (console, file) and format are completely defined by ourselves * * / / / system out. println(123);         Logger logger = LoggerFactory. getLogger(SKF4JTest.class);         try {            Class.forName(“aaa”); } < strong > catch < / strong > (classnotfoundexception E) {/ / print stack tracking information / / e.printstacktrace(); logger.info (< strong > The < / strong > < strong > XXX < / strong > < strong > method in the “XXX < / strong > < strong > class is abnormal < / strong > < strong >, < / strong > < strong > please pay attention to the information in time < / strong > < strong >” < / strong >); / / E is an application type object and cannot be spliced with a valid string based on the {} in front of the root / / logger Info (“the specific error is: {}”, e); / / we don’t need to add {}, just add the exception object after {logger Info (< strong > “< / strong > < strong > the specific error is < / strong > < strong >:” < / strong >, e);         }    }

Try to integrate slf4j with multiple logs at the same time to analyze the results

Introduce dependency

<!–logback的依赖–>    <dependency>        <groupId>ch.qos.logback</groupId>        <artifactId>logback-classic</artifactId>        <version>1.2.3</version>    </dependency>

use:

@Testpublic void test04() {/ * * before integrating other logs * observe the official website * slf4j log facade. There are three ways to bind logs * 1. On the basis of not binding any logs, logs cannot be bound to achieve any functions * it is worth noting that through the case we just demonstrated, slfj simple is provided by the slf4j official website * when used You also need to import dependencies. Slf4j core dependencies do not provide any implementation * 2 Logback and simple (including NOP) * are the log implementations provided behind the slf4j facade timeline, so the API completely follows the design of slf4j * then we only need to import the log implementation dependencies we want to use to seamlessly connect with slf4j * it is worth mentioning that although NOP is also divided into implementations, However, he refers to the log records from time to time (mentioned later) * 3 Log4j and Jul * are log implementations in front of slf4j’s facade timeline, so the API is not designed in accordance with slf4j * the connection with the log facade is completed through adaptive bridging technology * * the logback framework is integrated * * test 1: * based on the original slf4j = simple log implementation, Lombok * is also integrated. Through this test, the log is printed out in Java Lang. classnotfoundexception: AAA * slf4j: actual binding is of type [org. Slf4j. Impl. Simpleloggerfactory] * although Lombok is integrated, we still use slf4j simple * in fact, as long as this reference slf4j: class path contains multiple slf4j bindings * in the slf4j environment, it is proved that multiple log implementations occur at the same time * if POM If the first one in the XML file is logback, the dependency * * / logger = loggerfactory imported first is used getLogger(SKF4JTest.class);     try {        Class.forName(“aaa”); } < strong > catch < / strong > (classnotfoundexception E) {logger.info (< strong > “< / strong > < strong > the specific error is < / strong > < strong >:” < / strong >, e);     }}

Slf4j集成logback

Test: * comment out slf4j simple * leave only logback, then the slf4j facade uses logback log implementation * it is worth mentioning that there is no redundant prompt this time * so in the real development situation, a log integration can be implemented * * through this song integration test, we will find that although the underlying logs have changed, However, the source code has not changed at all * this is the log facade that brings us the greatest benefits * when logging at the bottom, the application does not need to know anything * the application only needs to remember slf4j the API