Spring Boot 笔记 - 轻松做日志(使用 slf4 和 log4j2)

POM.xml

使用 slf4(接口)log4j2(实现) 做日志框架. 首先干掉自带的 starter-logging, 那是 logback, 然后使用 lombok 插件来简化工作.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring-boot-starter-logging</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

用法

都差不多的用法, 不过可以用 {} 做字符串拼接, 比较舒服.

然后要加注解 Log4j2, 这是 lombok 提供的.

@RestController
@Log4j2
public class Controller {
    @GetMapping("/users/{id}")
    public Optional<User> getOne(@PathVariable Long id) {
        log.trace("require user {} info", id);
        log.debug("require user {} info", id);
        log.info("require user {} info", id);
        log.warn("require user {} info", id);        
        return userService.getUserById(id);
    }
}

日志级别调整
application.yml中可以配置级别, 支持多项配置, root 意味着整个项目的日志级别, 某一个包则定义特定包的日志级别, 很容易理解.

logging:
  level:
    com.example.repo: warn
#   com.example.repo.service: warn
#   root: warn

猜你喜欢

转载自www.cnblogs.com/imzhizi/p/spring-boot-logging-easy-way.html