常見的Slf4j日誌打印有兩種方式,分別爲傳統方式和註解方式。html
示例:web
package com.example.demo.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import com.example.demo.service.HelloService; @RestController @RequestMapping("/Test") public class HelloWorld { @Autowired private HelloService helloService; private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class); @GetMapping("/hello") public String sayHello(){ logger.info("hello Sfl4j + logback......"); return helloService.sayHello(); } }
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
(若是註解@Slf4j注入後找不到變量log,那就給IDE安裝lombok插件)spring
經常使用IDEA安裝lombok插件,app
Settings→Plugins→Browse repositories→lombok pluginmaven
在線安裝不行,採用本地安裝,能夠參考:spa
http://www.javashuo.com/article/p-xxbbfsru-bb.html插件
package com.example.demo.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import com.example.demo.service.HelloService; @Slf4j @RestController @RequestMapping("/Test") public class HelloWorld { @Autowired private HelloService helloService; @GetMapping("/hello") public String sayHello(){ log.info("hello @Sfl4j + logback......"); return helloService.sayHello(); } }
註解方式較傳統方式更加簡單快捷,最直接的便利就是不用每次新建一個類時都要建立 logger,即:日誌
private final static Logger logger = LoggerFactory.getLogger(HelloWorld.class);