Spring Boot (教程十: 日志)

来源:互联网 发布:知乎寒武纪芯片 编辑:程序博客网 时间:2024/05/22 11:45

GitHub 地址:

https://github.com/asd821300801/Spring-Boot.git


使用SLF4J记录日志



在开发中我们不建议使用 System.out 因为大量的使用 System.out 会增加资源的消耗。
spring boot支持的日志框架有,logback,Log4j2,Log4j和Java Util Logging
spring Boot 提供了一套日志系统,logback是最优先的选择。


  • 在 src/main/resources 下面创建logback.xml (根据不同环境来定义不同的日志输出,那么取名为logback-spring.xml即可,官方优先推荐使用-spring.*的配置方式)文件。




创建配置文件


  • logback.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"/></configuration>

1



在代码中调用


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


完整代码


  • Slf4jController.java
  • 包所在:com.example.log


package com.example.log;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/log")public class Slf4jController { //日志    private Logger logger =  LoggerFactory.getLogger(this.getClass());    @RequestMapping("/log")    public String log(){        logger.info("当前类:com.example.log.Slf4jController");        return "日志测试。";    }}

访问:http://localhost:8080/log/log.action 之后打印输出日志

2


参考:http://www.iteye.com/topic/1144412