我将演示如何在 springboot 应用程序中按日期或大小滚动日志文件。
默认情况下,springboot 使用logback作为默认记录器,但是如果您仅使用application.properties来配置日志记录,则存在一些限制:
logging.level.=ERROR # this is the root logging level for all packages.
logging.level.com.test.sb1jt=DEBUG # this is the project-specific package logging level configuration
logging.file=springboot-logger.log # this is the logging target file
您可以看到,我们可以配置根日志记录级别和包日志记录级别,但是如果要按日期或大小滚动日志文件,该怎么办?
当 springboot 类路径中的文件具有以下名称之一时,Spring 引导将自动通过默认配置加载它:
建议使用倒数弹簧.xml。
我们可以在 src/main/res/logback-spring 中定义滚动策略.xml如下所示:
%black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable ${LOGS}/spring-boot-loggerbysize.log ${LOGS}/spring-boot-loggerbysize-%d{yyyy-MM-dd}.%i.log 1MB 6 3MB %d %p %C{1.} [%t] %m%n
然后,您可以通过运行打印大量日志的无限循环来进行测试。然后你会得到这些文件:
-rw-r--r-- 1 zzz staff 1.0M May 25 18:21 spring-boot-loggerbysize-2019-05-25.0.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:21 spring-boot-loggerbysize-2019-05-25.1.log
-rw-r--r-- 1 zzz staff 317K May 25 18:22 spring-boot-loggerbysize.log
我们可以在 src/main/res/logback-spring 中定义日期滚动策略.xml如下所示:
%black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C{1.}): %msg%n%throwable ${LOGS}/spring-boot-loggerbyate.log %d %p %C{1.} [%t] %m%n ${LOGS}/spring-boot-loggerbydate-%d{yyyy-MM-dd}.%i.log 1MB
Then you can test by running a infinite loop which print a lot of logs. Then you would get these files:
-rw-r--r-- 1 zzz staff 393K May 25 18:34 spring-boot-loggerbyate.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:31 spring-boot-loggerbydate-2019-05-25.0.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:31 spring-boot-loggerbydate-2019-05-25.1.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:31 spring-boot-loggerbydate-2019-05-25.2.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:32 spring-boot-loggerbydate-2019-05-25.3.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:32 spring-boot-loggerbydate-2019-05-25.4.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:32 spring-boot-loggerbydate-2019-05-25.5.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:33 spring-boot-loggerbydate-2019-05-25.6.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:33 spring-boot-loggerbydate-2019-05-25.7.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:33 spring-boot-loggerbydate-2019-05-25.8.log
-rw-r--r-- 1 zzz staff 1.0M May 25 18:34 spring-boot-loggerbydate-2019-05-25.9.log
可以通过阅读日志日志记录追加程序配置来获取有关回日志追加程序的详细信息。