当前位置:Gxlcms > PHP教程 > SpringBoot日志框架实践-hansonwang99的技术分享

SpringBoot日志框架实践-hansonwang99的技术分享

时间:2021-07-01 10:21:17 帮助过:26人阅读

这篇文章主要给大家分享了关于Spring Boot日志框架实践,代码部分也非常详细,有需要的小伙伴可以参考一下。


概述

Java应用中,日志一般分为以下5个级别:

  • ERROR 错误信息

  • WARN 警告信息

  • INFO 一般信息

  • DEBUG 调试信息

  • TRACE 跟踪信息

Spring Boot使用Apache的Commons Logging作为内部的日志框架,其仅仅是一个日志接口,在实际应用中需要为该接口来指定相应的日志实现。

SpringBt默认的日志实现是Java Util Logging,是JDK自带的日志包,此外SpringBt当然也支持Log4J、Logback这类很流行的日志实现。

统一将上面这些日志实现统称为日志框架

下面我们来实践一下!


使用Spring Boot Logging插件

  • 首先application.properties文件中加配置:

  1. logging.level.root=INFO
  • 控制器部分代码如下:

  1. package com.hansonwang99.controller;
  2. import com.hansonwang99.K8sresctrlApplication;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. @RestController
  9. @RequestMapping("/testlogging")
  10. public class LoggingTestController {
  11. private static Logger logger = LoggerFactory.getLogger(K8sresctrlApplication.class);
  12. @GetMapping("/hello")
  13. public String hello() {
  14. logger.info("test logging...");
  15. return "hello";
  16. }
  17. }
  • 运行结果

由于将日志等级设置为INFO,因此包含INFO及以上级别的日志信息都会打印出来

这里可以看出,很多大部分的INFO日志均来自于SpringBt框架本身,如果我们想屏蔽它们,可以将日志级别统一先全部设置为ERROR,这样框架自身的INFO信息不会被打印。然后再将应用中特定的包设置为DEBUG级别的日志,这样就可以只看到所关心的包中的DEBUG及以上级别的日志了。

  • 控制特定包的日志级别

application.yml中改配置

  1. logging:
  2. level:
  3. root: error
  4. com.hansonwang99.controller: debug

很明显,将root日志级别设置为ERROR,然后再将com.hansonwang99.controller包的日志级别设为DEBUG,此即:即先禁止所有再允许个别的 设置方法

  • 控制器代码

  1. package com.hansonwang99.controller;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. @RequestMapping("/testlogging")
  9. public class LoggingTestController {
  10. private Logger logger = LoggerFactory.getLogger(this.getClass());
  11. @GetMapping("/hello")
  12. public String hello() {
  13. logger.info("test logging...");
  14. return "hello";
  15. }
  16. }
  • 运行结果

可见框架自身的INFO级别日志全部藏匿,而指定包中的日志按级别顺利地打印出来

  • 将日志输出到某个文件中

  1. logging:
  2. level:
  3. root: error
  4. com.hansonwang99.controller: debug
  5. file: ${user.home}/logs/hello.log
  • 运行结果

使用Spring Boot Logging,我们发现虽然日志已输出到文件中,但控制台中依然会打印一份,发现用org.slf4j.Logger是无法解决这个问题的


集成Log4J日志框架

  • pom.xml中添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-logging</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-log4j2</artifactId>
  14. </dependency>
  • 在resources目录下添加log4j2.xml文件,内容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <appenders>
  4. <File name="file" fileName="${sys:user.home}/logs/hello2.log">
  5. <PatternLayout pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"/>
  6. </File>
  7. </appenders>
  8. <loggers>
  9. <root level="ERROR">
  10. <appender-ref ref="file"/>
  11. </root>
  12. <logger name="com.hansonwang99.controller" level="DEBUG" />
  13. </loggers>
  14. </configuration>
  • 其他代码都保持不变

运行程序发现控制台没有日志输出,而hello2.log文件中有内容,这符合我们的预期:

而且日志格式和pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"格式中定义的相匹配


Log4J更进一步实践

  • pom.xml配置:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. <exclusions>
  5. <exclusion>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-logging</artifactId>
  8. </exclusion>
  9. </exclusions>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-log4j2</artifactId>
  14. </dependency>
  • log4j2.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration status="warn">
  3. <properties>
  4. <Property name="app_name">springboot-web</Property>
  5. <Property name="log_path">logs/${app_name}</Property>
  6. </properties>
  7. <appenders>
  8. <console name="Console" target="SYSTEM_OUT">
  9. <PatternLayout pattern="[%d][%t][%p][%l] %m%n" />
  10. </console>
  11. <RollingFile name="RollingFileInfo" fileName="${log_path}/info.log"
  12. filePattern="${log_path}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz">
  13. <Filters>
  14. <ThresholdFilter level="INFO" />
  15. <ThresholdFilter level="WARN" onMatch="DENY"
  16. onMismatch="NEUTRAL" />
  17. </Filters>
  18. <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
  19. <Policies>
  20. <!-- 归档每天的文件 -->
  21. <TimeBasedTriggeringPolicy interval="1" modulate="true" />
  22. <!-- 限制单个文件大小 -->
  23. <SizeBasedTriggeringPolicy size="2 MB" />
  24. </Policies>
  25. <!-- 限制每天文件个数 -->
  26. <DefaultRolloverStrategy compressionLevel="0" max="10"/>
  27. </RollingFile>
  28. <RollingFile name="RollingFileWarn" fileName="${log_path}/warn.log"
  29. filePattern="${log_path}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz">
  30. <Filters>
  31. <ThresholdFilter level="WARN" />
  32. <ThresholdFilter level="ERROR" onMatch="DENY"
  33. onMismatch="NEUTRAL" />
  34. </Filters>
  35. <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
  36. <Policies>
  37. <!-- 归档每天的文件 -->
  38. <TimeBasedTriggeringPolicy interval="1" modulate="true" />
  39. <!-- 限制单个文件大小 -->
  40. <SizeBasedTriggeringPolicy size="2 MB" />
  41. </Policies>
  42. <!-- 限制每天文件个数 -->
  43. <DefaultRolloverStrategy compressionLevel="0" max="10"/>
  44. </RollingFile>
  45. <RollingFile name="RollingFileError" fileName="${log_path}/error.log"
  46. filePattern="${log_path}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
  47. <ThresholdFilter level="ERROR" />
  48. <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
  49. <Policies>
  50. <!-- 归档每天的文件 -->
  51. <TimeBasedTriggeringPolicy interval="1" modulate="true" />
  52. <!-- 限制单个文件大小 -->
  53. <SizeBasedTriggeringPolicy size="2 MB" />
  54. </Policies>
  55. <!-- 限制每天文件个数 -->
  56. <DefaultRolloverStrategy compressionLevel="0" max="10"/>
  57. </RollingFile>
  58. </appenders>
  59. <loggers>
  60. <root level="info">
  61. <appender-ref ref="Console" />
  62. <appender-ref ref="RollingFileInfo" />
  63. <appender-ref ref="RollingFileWarn" />
  64. <appender-ref ref="RollingFileError" />
  65. </root>
  66. </loggers>
  67. </configuration>
  • 控制器代码:

  1. package com.hansonwang99.controller;
  2. import org.apache.logging.log4j.LogManager;
  3. import org.apache.logging.log4j.Logger;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. @RestController
  8. @RequestMapping("/testlogging")
  9. public class LoggingTestController {
  10. private final Logger logger = LogManager.getLogger(this.getClass());
  11. @GetMapping("/hello")
  12. public String hello() {
  13. for(int i=0;i<10_0000;i++){
  14. logger.info("info execute index method");
  15. logger.warn("warn execute index method");
  16. logger.error("error execute index method");
  17. }
  18. return "My First SpringBoot Application";
  19. }
  20. }
  • 运行结果

日志会根据不同的级别存储在不同的文件,当日志文件大小超过2M以后会分多个文件压缩存储,生产环境的日志文件大小建议调整为20-50MB。


后记

作者更多的原创文章见SF专栏

作者更多的SpringBt实践文章在此:

  • ElasticSearch搜索引擎在SpringBoot中的实践

  • 初探Kotlin+SpringBoot联合编程



相关推荐:

java程序员最常用的8个Java日志框架

以上就是Spring Boot日志框架实践 - hansonwang99的技术分享 的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行