重生之 SpringBoot3 入门保姆级学习(10、日志基础使用)
- 3.1 日志基础
- 3.2 使用日志
- 3.2.1 基础使用
- 3.2.2 调整日志级别
- 3.2.3 带参数的日志
3.1 日志基础
- SpringBoot 默认使用 SLF4j(Simple Logging Facade for Java)和 Logback 实现日志,默认日志级别是 INFO
- 日志级别有
- ALL 打印所有日志
- TRACE 追踪框架详细流程日志,一般不用
- DEBUG 开发者调试日志
- INFO 关键、感兴趣的日志
- WARN 警告但不是错误信息的日志,比如:版本过时
- ERROR 业务错误日志,比如:出现各种异常
- FATAL 致命日志错误,比如:jvm 系统崩溃
- OFF 关闭所有日志

- SpringBoot 默认日志输出格式
- 外部库 -> Maven: org.springframework.boot:spring-boot:3.2.5 -> META-INF -> additional-spring-configuration-metadata.json
%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd'T'HH:mm:ss.SSSXXX}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}

- 通过 application.properties 修改日志输出格式
logging.pattern.console=%d{yyyy-MM-dd HH:mm:SS} %-5level [%thread] %logger{15} ===> %msg%n

logging.pattern.dateformat=yyyy-MM-dd HH:mm:ss.SSS
3.2 使用日志
3.2.1 基础使用
- 编写 Controller 层 HelloController
package com.zhong.logging.controller;
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 {
Logger logger = LoggerFactory.getLogger(getClass());
@GetMapping("/h")
public String Hello() {
logger.info("哈哈哈,方法进来了。");
return "hello";
}
}
package com.zhong.logging.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class HelloController {
@GetMapping("/h")
public String Hello() {
log.info("哈哈哈,方法进来了。");
return "hello";
}
}
http://localhost:8080/h


3.2.2 调整日志级别
# 调整该项目的所有日志级别
logging.level.root = debug
# 调整该类下的所有日志级别
logging.level.com.zhong.logging.controller.HelloController = info

3.2.3 带参数的日志
package com.zhong.logging.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class HelloController {
@GetMapping("/h")
public String Hello(String a, String b) {
log.info("哈哈哈,方法进来了。参数: {} {}", a, b);
return "hello";
}
}
http://localhost:8080/h

http://localhost:8080/h?a=10&b=20
