Spring Boot使用Spring框架的Commons Logging作为默认的日志框架,同时也支持使用其他流行的日志框架,如Logback、Log4j2等。在Spring Boot中,可以通过配置文件来对日志进行配置,包括日志级别、输出格式、日志文件等。
- 在 application.properties 或 application.yml 中配置日志属性:
在 application.properties 中添加如下配置:
#配置日志级别
logging.level.root=INFO
#配置日志输出格式
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
#配置日志文件
logging.file=myapp.log
- 在 pom.xml 中添加对应的日志框架依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
- 在应用程序中使用日志:
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 LogController {
private static final Logger logger = LoggerFactory.getLogger(LogController.class);
@GetMapping("/log")
public String logMessage() {
logger.debug("This is a debug message");
logger.info("This is an info message");
logger.error("This is an error message");
return "Logging example";
}
}
在这个示例中,配置了日志级别为INFO,输出格式为自定义格式,日志文件为 myapp.log 。在 LogController 中,使用SLF4J日志门面接口来获取Logger实例,并在不同级别下输出日志信息。
原文链接: https://blog.csdn.net/2401_82884096/article/details/138295015