(44). Spring Boot日志记录SLF4J【从零开始学Spring Boot】

来源:互联网 发布:网络推手阿建可以信赖 编辑:程序博客网 时间:2024/04/29 08:32

在开发中打印内容,使用 System.out.println()  Log4j 应当是人人皆知的方法了。

其实在开发中我们不建议使用 System.out 因为大量的使用 System.out 会增加资源的消耗。

Log4j 更为灵活在性能上也相比 System.out 要高,我们可以配置输出级别,可以指定多个日志文件分别记录不同的日志。

       使用 System.out 是在当前线程执行的,写入文件也是写入完毕后才继续执行下面的程序。而使用Log工具不但可以控制日志是否输出,怎么输出,它的处理机制也是通知写日志,继续执行后面的代码不必等日志写完。

如非必要,建议大家不要使用控制台输出,因为控制台输出没有优先级会显得输出太乱。

       个人推荐使用 SLF4JSimple Logging Facade For Java)的logback来输出日志,其比log4j 要好,因为他效率更高。

       Spring Boot 提供了一套日志系统,logback是最优先的选择。

       Spring Boot 中记录日志只需两步: 
1
、在 src/main/resources 下面创建logback.xml (根据不同环境来定义不同的日志输出,那么取名为logback-spring.xml 即可文件,并按上面讲述的进行配置。 
或者使用最简单的方法在 application 配置文件中配置。 
2
、在Java代码中创建实例,并在需要输出日志的地方使用。

logback-spring.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>

<configuration>

    <include resource="org/springframework/boot/logging/logback/base.xml" />

    <logger name="org.springframework.web" level="INFO"/>

    <logger name="org.springboot.sample" level="TRACE" />

 

    <springProfile name="dev">

        <logger name="org.springboot.sample" level="DEBUG" />

    </springProfile>

 

    <springProfile name="staging">

        <logger name="org.springboot.sample" level="INFO" />

    </springProfile>

</configuration>

 

在代码中调用:

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

private Logger logger =  LoggerFactory.getLogger(this.getClass());

 

 

0 0
原创粉丝点击