springboot lombok slf4j logback集成
时间: 2023-09-16 22:10:26 浏览: 235
集成Spring Boot、Lombok、SLF4J和Logback有以下几个步骤:
1. 引入依赖:在`pom.xml`文件中引入以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Lombok依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- SLF4J依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- Logback依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
```
2. 创建日志配置文件:在`src/main/resources`目录下创建`logback.xml`文件,并在其中配置日志输出格式、日志级别等信息。示例配置文件如下:
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 定义日志输出格式 -->
<property name="LOG_PATTERN" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
<!-- 控制台输出 -->
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- 文件输出 -->
<appender name="fileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/spring-boot-demo.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/spring-boot-demo-%d{yyyy-MM-dd}.log</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- 定义日志级别 -->
<root level="INFO">
<appender-ref ref="consoleAppender"/>
<appender-ref ref="fileAppender"/>
</root>
</configuration>
```
3. 在代码中使用SLF4J:使用SLF4J的API进行日志输出,示例代码如下:
```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);
@GetMapping("/hello")
public String hello() {
LOGGER.debug("debug message");
LOGGER.info("info message");
LOGGER.warn("warn message");
LOGGER.error("error message");
return "Hello, world!";
}
}
```
4. 使用Lombok简化代码:使用Lombok注解简化代码,示例代码如下:
```
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class HelloController {
@GetMapping("/hello")
public String hello() {
log.debug("debug message");
log.info("info message");
log.warn("warn message");
log.error("error message");
return "Hello, world!";
}
}
```
以上就是集成Spring Boot、Lombok、SLF4J和Logback的步骤。
阅读全文