跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Spring Boot日志
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Spring Boot日志 = == 介绍 == '''Spring Boot日志'''是Spring框架中用于记录应用程序运行时信息的重要组件。它基于SLF4J(Simple Logging Facade for Java)和Logback(默认实现),提供了统一的日志接口和灵活的配置选项。日志系统帮助开发者调试代码、监控应用状态并追踪异常行为。 Spring Boot通过自动配置简化了日志系统的设置,开发者只需关注业务逻辑而无需手动初始化日志框架。日志级别(如DEBUG、INFO、WARN、ERROR)和输出格式均可通过配置文件调整。 == 核心概念 == === 日志级别 === Spring Boot支持以下标准日志级别(从低到高): * <code>TRACE</code> - 最详细的跟踪信息 * <code>DEBUG</code> - 调试信息 * <code>INFO</code> - 常规运行信息(默认级别) * <code>WARN</code> - 警告事件 * <code>ERROR</code> - 错误事件 * <code>FATAL</code> - 严重错误导致应用终止 === 日志框架结构 === <mermaid> graph TD A[Application] -->|调用| B[SLF4J API] B -->|绑定| C[Logback] B -->|绑定| D[Log4j2] B -->|绑定| E[JUL] </mermaid> == 基础配置 == === 默认日志输出 === Spring Boot自动配置的日志会输出到控制台,格式如下: <syntaxhighlight lang="text"> 2023-05-20 14:30:45.123 INFO 12345 --- [main] com.example.MyApp : Starting MyApp </syntaxhighlight> === 修改日志级别 === 在<code>application.properties</code>中配置: <syntaxhighlight lang="properties"> # 设置root日志级别 logging.level.root=WARN # 设置特定包日志级别 logging.level.com.example=DEBUG </syntaxhighlight> == 代码示例 == === 基本日志记录 === <syntaxhighlight lang="java"> 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 { // 获取Logger实例 private static final Logger logger = LoggerFactory.getLogger(LogController.class); @GetMapping("/test") public String testLogging() { logger.trace("This is TRACE message"); logger.debug("This is DEBUG message"); logger.info("This is INFO message"); logger.warn("This is WARN message"); logger.error("This is ERROR message"); return "Check console for logs"; } } </syntaxhighlight> '''输出示例'''(当<code>logging.level.com.example=DEBUG</code>时): <syntaxhighlight lang="text"> 2023-05-20 14:35:22.456 DEBUG 12345 --- [nio-8080-exec-1] com.example.LogController : This is DEBUG message 2023-05-20 14:35:22.456 INFO 12345 --- [nio-8080-exec-1] com.example.LogController : This is INFO message 2023-05-20 14:35:22.456 WARN 12345 --- [nio-8080-exec-1] com.example.LogController : This is WARN message 2023-05-20 14:35:22.456 ERROR 12345 --- [nio-8080-exec-1] com.example.LogController : This is ERROR message </syntaxhighlight> == 高级配置 == === 自定义日志格式 === 在<code>application.properties</code>中: <syntaxhighlight lang="properties"> # 控制台日志模式 logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n # 文件日志模式 logging.pattern.file=%d{yyyy-MM-dd} [%thread] %-5level %logger{36} - %msg%n </syntaxhighlight> === 日志文件输出 === <syntaxhighlight lang="properties"> # 输出到指定文件 logging.file.name=app.log # 或按大小轮转(Logback特性) logging.logback.rollingpolicy.max-file-size=10MB logging.logback.rollingpolicy.max-history=7 </syntaxhighlight> == 实际应用案例 == === 异常监控 === <syntaxhighlight lang="java"> @RestController public class OrderController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @PostMapping("/orders") public ResponseEntity<?> createOrder(@RequestBody Order order) { try { // 业务逻辑 return ResponseEntity.ok("Order created"); } catch (Exception e) { logger.error("Failed to create order: {}", order, e); return ResponseEntity.status(500).body("Error creating order"); } } } </syntaxhighlight> '''日志输出''': <syntaxhighlight lang="text"> 2023-05-20 14:40:33.789 ERROR 12345 --- [nio-8080-exec-2] com.example.OrderController : Failed to create order: Order(id=null, product=ABC) java.lang.NullPointerException: Cannot invoke "com.example.Order.getId()" because the return value of "com.example.Service.process(com.example.Order)" is null at com.example.OrderController.createOrder(OrderController.java:25) ... </syntaxhighlight> === 性能日志 === 使用AOP记录方法执行时间: <syntaxhighlight lang="java"> @Aspect @Component public class LoggingAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Around("execution(* com.example.service.*.*(..))") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = joinPoint.proceed(); long duration = System.currentTimeMillis() - startTime; logger.info("{} executed in {} ms", joinPoint.getSignature(), duration); return result; } } </syntaxhighlight> == 数学公式示例 == 当需要计算日志采样率时,可能用到以下公式: 采样概率公式: <math>P = \frac{1}{n}</math> 其中: * <math>P</math> 为采样概率 * <math>n</math> 为采样率基数 == 最佳实践 == 1. 生产环境建议使用<code>WARN</code>作为默认级别 2. 敏感信息不应记录在日志中 3. 使用<code>{}</code>占位符而非字符串拼接(更高效) 4. 重要业务操作建议记录审计日志 5. 分布式系统考虑集中式日志收集(如ELK) == 常见问题 == '''Q: 如何切换日志实现(如从Logback到Log4j2)?''' A: 排除默认依赖并添加Log4j2 starter: <syntaxhighlight lang="xml"> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> </syntaxhighlight> '''Q: 为什么我的DEBUG日志没有输出?''' A: 检查: 1. <code>application.properties</code>中的日志级别设置 2. 是否有多个配置文件冲突 3. 是否在启动命令中覆盖了日志级别(如<code>--debug</code>参数) [[Category:后端框架]] [[Category:Spring]] [[Category:Spring Boot]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)