A Guide to Rolling File Appenders – 滚动文件应用者指南

最后修改: 2016年 12月 27日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

While log files often convey useful information, they naturally grow bigger over time. If allowed to grow indefinitely, their size could become a problem.

虽然日志文件经常传达有用的信息,但随着时间的推移,它们自然会变大。如果允许无限期地增长,它们的大小可能成为一个问题。

Logging libraries address this problem using rolling file appenders, which automatically “roll” or archive the current log file, and resume logging in a new file when certain predefined conditions occur, thereby preventing unwanted downtime.

日志库使用滚动文件附加程序来解决这个问题,它自动 “滚动 “或归档当前的日志文件,并在某些预定义条件发生时在新文件中恢复日志记录,从而防止不必要的停机。

In this tutorial, we’ll learn how to configure rolling file appenders in some of the most widely used logging libraries: Log4j, Log4j2, and Slf4j.

在本教程中,我们将学习如何在一些最广泛使用的日志库中配置滚动文件appender。Log4j、Log4j2和Slf4j。

We’ll demonstrate how to roll log files based on size, date/time, and a combination of size and date/time. We’ll also explore how to configure each library to automatically compress, and later delete, the old log files, saving us from writing tedious housekeeping code.

我们将演示如何根据大小、日期/时间以及大小和日期/时间的组合来滚动日志文件。我们还将探讨如何配置每个库,使其自动压缩,并在以后删除旧的日志文件,从而使我们免于编写繁琐的内务管理代码。

2. Our Sample Application

2.我们的应用样本

Let’s start with an example application that logs some messages. This code is based on Log4j, but we can easily modify it to work with Log4j2 or Slf4j:

让我们从一个记录一些信息的应用程序的例子开始。这段代码是基于Log4j的,但我们可以很容易地修改它,使之与Log4j2或Slf4j一起工作。

import org.apache.log4j.Logger;

public class Log4jRollingExample {

    private static Logger logger = Logger.getLogger(Log4jRollingExample.class);

    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 2000; i++) {
            logger.info("This is the " + i + " time I say 'Hello World'.");
            Thread.sleep(100);
        }
    }
}

The application is quite naive; it writes some messages in a loop, with a short delay between iterations. With 2,000 loops to run, and a pause of 100 ms in each loop, the application should take a little more than three minutes to complete.

这个应用程序是相当幼稚的;它在一个循环中写一些信息,迭代之间有短暂的延迟。有2000个循环要运行,每个循环有100毫秒的停顿,这个应用程序应该需要三分钟多一点的时间来完成。

We’ll use this sample to demonstrate several features of different kinds of rolling file appenders.

我们将用这个样本来演示不同种类的滚动文件应用程序的几个特点。

3. Rolling File Appenders in Log4j

3.Log4j中的滚动文件应用者

3.1. Maven Dependencies

3.1.Maven的依赖性

First, to use Log4j in our application, we’ll add this dependency to our project’s pom.xml file:

首先,为了在我们的应用程序中使用Log4j,我们将在我们项目的pom.xml文件中添加这个依赖。

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

For the additional appenders provided by apache-log-extras that we’ll use in the next examples, we’ll add the following dependency, being sure to use the same version that we declared for Log4j in order to ensure full compatibility:

对于我们将在接下来的例子中使用的由apache-log-extras提供的额外appenders,我们将添加以下依赖,确保使用与我们为Log4j声明的相同版本,以确保完全兼容。

<dependency>
    <groupId>log4j</groupId>
    <artifactId>apache-log4j-extras</artifactId>
    <version>1.2.17</version>
</dependency>

We can find the latest release of Log4j and Apache Log4j Extras on Maven Central.

我们可以在Maven中心找到Log4jApache Log4j Extras的最新版本。

3.2. Rolling Based on File Size

3.2.基于文件大小的滚动

In Log4j, as in other logging libraries, file rolling is delegated to the appender. Let’s look at the configuration for a rolling file appender in Log4j that rolls based on file size:

在Log4j中,和其他日志库一样,文件滚动被委托给appender。让我们看看Log4j中基于文件大小滚动的文件appender的配置。

<appender name="roll-by-size" class="org.apache.log4j.RollingFileAppender">
    <param name="file" value="target/log4j/roll-by-size/app.log" />
    <param name="MaxFileSize" value="5KB" />
    <param name="MaxBackupIndex" value="2" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n" />
        </layout>
</appender>

Here we configured Log4j to roll the log file when its size reaches 5KB using the MaxFileSize parameter. We also instructed Log4j to keep a maximum of two rolled log files using the MaxBackupIndex parameter.

在这里,我们使用MaxFileSize参数配置了Log4j在日志文件大小达到5KB时进行滚动。我们还使用MaxBackupIndex参数指示Log4j最多保留两个滚动的日志文件。

When we run our sample application, we obtain the following files:

当我们运行我们的示例应用程序时,我们获得了以下文件。

27/11/2016  10:28    138 app.log
27/11/2016  10:28  5.281 app.log.1
27/11/2016  10:28  5.281 app.log.2

So what happened? Log4j started writing to the app.log file. When the file size exceeded the 5KB limit, Log4j moved app.log to app.log.1, created a new empty app.log, and continued writing new log messages to app.log.

那么发生了什么?Log4j开始向app.log文件写入。当文件大小超过5KB限制时,Log4j将app.log移到app.log.1,创建了一个新的空app.log,并继续向app.log写新的日志消息。

Then, after the new app.log exceeded the 5KB limit, this rolling process was repeated. This time, app.log.1 was moved to app.log.2, making room for another new empty app.log.

然后,在新的app.log超过了5KB的限制后,这个滚动过程又被重复了。这一次,app.log.1被移到app.log.2,为另一个新的空app.log腾出空间。

This rolling process was repeated several times during the run, but since we configured our appender to keep two rolled files at most, there isn’t a file called app.log.3.

这个滚动过程在运行过程中重复了好几次,但是由于我们将appender配置为最多保留两个滚动的文件,所以并没有一个叫做app.log.3的文件。

So we solved one of the original problems because now we can set up a limit on the size of the produced log files.

所以我们解决了原来的一个问题,因为现在我们可以对产生的日志文件的大小设置一个限制。

When we check the first line of app.log.2, it contains the message related to the 700th iteration, meaning all previous log messages were lost:

当我们检查app.log.2的第一行时,它包含了与第700次迭代有关的信息,这意味着之前的所有日志信息都丢失了。

2016-11-27 10:28:34 INFO  This is the 700 time I say 'Hello World'.

Now let’s see if we can devise a setup better suited to a production environment, where losing log messages isn’t considered the best approach.

现在让我们看看我们是否能设计出一个更适合生产环境的设置,在那里丢失日志信息并不是最好的办法。

To do this, we’ll use other more powerful, flexible, and configurable Log4j appenders that are shipped in a dedicated package, called apache-log4j-extras.

要做到这一点,我们将使用其他更强大、更灵活、更可配置的Log4j应用程序,这些程序在一个专门的软件包中发货,称为apache-log4j-extras

The appenders contained in this artifact offer lots of options to fine tune the log rolling, and they introduce the distinct concepts of triggering policy and rolling policy. The triggering policy describes when a roll should occur, while the rolling policy describes how the rolling should be carried out. These two concepts are key to rolling log files, and other libraries use them more or less explicitly as well.

这个工件中包含的附加程序提供了很多选项来微调日志滚动,它们引入了触发策略滚动策略的不同概念。触发策略描述了何时应该发生滚动,而滚动策略描述了应该如何进行滚动。这两个概念是滚动日志文件的关键,其他库也或多或少地明确使用它们。

3.3. Rolling With Automatic Compression

3.3.带自动压缩功能的轧制

Let’s go back to the Log4j example and improve our setup by adding the automatic compression of the rolled files to save space:

让我们回到Log4j的例子中,通过增加自动压缩滚动文件以节省空间来改进我们的设置。

<appender name="roll-by-size" class="org.apache.log4j.rolling.RollingFileAppender">
    <rollingPolicy class="org.apache.log4j.rolling.FixedWindowRollingPolicy">
        <param name="ActiveFileName" value="target/log4j/roll-by-size/app.log" />
        <param name="FileNamePattern" value="target/log4j/roll-by-size/app.%i.log.gz" />
    <param name="MinIndex" value="7" />
    <param name="MaxIndex" value="17" /> 
    </rollingPolicy>
    <triggeringPolicy class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
        <param name="MaxFileSize" value="5120" />
    </triggeringPolicy>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n" />
    </layout>
</appender>

With the triggering policy element, we stated that the roll should occur when the log exceeds the size of 5,120 bytes.

通过触发策略元素,我们指出,当日志超过5120字节的大小时,应该发生滚动。

Within the rolling policy tag, the ActiveFileName parameter states the path of the main log files containing the latest messages, and the FileNamePattern parameter specifies a template describing what the path of the rolled files should be. Let’s note that this is indeed a pattern because the special placeholder %i will be replaced with the index of the rolled file.

滚动策略标签中,ActiveFileName参数说明了包含最新消息的主要日志文件的路径,而FileNamePattern参数指定了一个模板,描述了滚动文件的路径应该是什么。让我们注意,这确实是一个模式,因为特殊的占位符%i将被替换成滚动文件的索引。

Let’s also note that FileNamePattern ends with a “.gz” extension. Whenever we use an extension associated with a supported compressed format, we’ll have the old rolled files compressed without any extra effort from our side.

让我们也注意到,FileNamePattern以”.gz”扩展名结束。每当我们使用一个与支持的压缩格式相关的扩展名时,我们就会让旧的滚动文件被压缩,而不需要从我们这边做任何额外的努力。

Now when we run the application, we obtain a different set of log files:

现在,当我们运行该应用程序时,我们获得了一组不同的日志文件。

03/12/2016 19:24 88 app.1.log.gz
...
03/12/2016 19:26 88 app.2.log.gz
03/12/2016 19:26 88 app.3.log.gz
03/12/2016 19:27 70 app.current.log

The file app.current.log is where the last logs occurred. The previous logs are rolled and compressed when their size reaches the set limit.

文件app.current.log是最后一次日志发生的地方。以前的日志在其大小达到设定的限制时被滚动和压缩。

3.4. Rolling Based on Date and Time

3.4.基于日期和时间的滚动

In other scenarios, we may want to configure Log4j to roll the files based on the date and time of the log messages, instead of the size of the file. In a web application, for instance, we may want to have all the log messages issued in one day in the same log file.

在其他情况下,我们可能想配置Log4j,使其根据日志信息的日期和时间,而不是文件的大小来滚动文件。例如,在一个Web应用程序中,我们可能想把一天内发出的所有日志信息放在同一个日志文件中。

To do this, we can use the TimeBasedRollingPolicy. With this policy, it’s mandatory to specify a template for the path of the log file that contains a time-related placeholder. Each time a log message is issued, the appender verifies what the resulting log path will be. If it differs from the last used path, then a roll will occur. Here’s a quick example that configures such an appender:

要做到这一点,我们可以使用TimeBasedRollingPolicy。有了这个策略,就必须为日志文件的路径指定一个模板,其中包含一个与时间有关的占位符。每次发布日志消息时,appender都会验证产生的日志路径是什么。如果它与上次使用的路径不同,那么就会发生滚动。这里有一个快速的例子,配置了这样一个appender。

<appender name="roll-by-time"
    class="org.apache.log4j.rolling.RollingFileAppender">
    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="FileNamePattern" value="target/log4j/roll-by-time/app.%d{HH-mm}.log.gz" />
    </rollingPolicy>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n" />
    </layout>
</appender>

3.5. Rolling Based on Size and Time

3.5.基于规模和时间的滚动

Combining the SizeBasedTriggeringPolicy and the TimeBasedRollingPolicy, we can obtain an appender that rolls based on date/time, and when the size of the file reaches the set limit, it rolls based on size too:

结合SizeBasedTriggeringPolicyTimeBasedRollingPolicy,我们可以得到一个基于日期/时间滚动的appender,当文件的大小达到设定的限制时,它也基于大小滚动。

<appender name="roll-by-time-and-size" class="org.apache.log4j.rolling.RollingFileAppender">
    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="ActiveFileName" value="log4j/roll-by-time-and-size/app.log" />
        <param name="FileNamePattern" value="log4j/roll-by-time-and-size/app.%d{HH-mm}.%i.log.gz" />
    </rollingPolicy>
    <triggeringPolicy
        class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
        <param name="MaxFileSize" value="100" />
    </triggeringPolicy>
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n" />
    </layout>
</appender>

When we run our application with this setup, we obtain the following log files:

当我们用这种设置运行我们的应用程序时,我们获得了以下日志文件。

03/12/2016 19:25 234 app.19-25.1481393432120.log.gz
03/12/2016 19:25 234 app.19-25.1481393438939.log.gz
03/12/2016 19:26 244 app.19-26.1481393441940.log.gz
03/12/2016 19:26 240 app.19-26.1481393449152.log.gz
03/12/2016 19:26 3.528 app.19-26.1481393470902.log

The file app.19-26.1481393470902.log is where the current logging takes place. As we can see, all the logs in the interval between 19:25 and 19:26 are stored in multiple compressed log files with names starting with “app.19-25″. The “%i” placeholder is replaced by an ever increasing number.

文件app.19-26.1481393470902.log是当前日志记录发生的地方。正如我们所看到的,19:25和19:26之间的所有日志都存储在多个压缩的日志文件中,文件名以”app.19-25″开头。“%i”占位符被一个不断增加的数字取代。

4. Rolling File Appenders in Log4j2

4.Log4j2中的滚动文件应用程序

4.1. Maven Dependencies

4.1.Maven的依赖性

To use Log4j2 as our preferred logging library, we need to update our project’s POM with the following dependency:

为了使用Log4j2作为我们的首选日志库,我们需要更新我们项目的POM,加入以下依赖关系。

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>

As usual, we can find the latest version on Maven Central.

像往常一样,我们可以在Maven中心找到最新的版本

4.2. Rolling Based on File Size

4.2.基于文件大小的滚动

Let’s change our example application to use the Log4j2 logging libraries. We’ll set up file rolling based on the size of the log file in the log4j2.xml configuration file:

让我们改变我们的示例应用程序以使用Log4j2日志库。我们将在log4j2.xml配置文件中根据日志文件的大小设置文件滚动。

<RollingFile 
  name="roll-by-size" 
  fileName="target/log4j2/roll-by-size/app.log"
  filePattern="target/log4j2/roll-by-size/app.%i.log.gz" 
  ignoreExceptions="false">
    <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
    </PatternLayout>
    <Policies>
        <OnStartupTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="5 KB" />
    </Policies>
</RollingFile>

In the Policies tag, we specified all the triggering policies we want to apply. OnStartupTriggeringPolicy triggers a roll every time the application starts, which can be useful for stand-alone applications. We also specified a SizeBasedTriggeringPolicy, stating that a roll should occur whenever the log file reaches 5KB.

Policies标签中,我们指定了所有我们要应用的触发策略。OnStartupTriggeringPolicy每次应用程序启动时都会触发滚动,这对独立的应用程序很有用。我们还指定了一个SizeBasedTriggeringPolicy,指出只要日志文件达到5KB就应该进行滚动。

4.3. Rolling Based on Date and Time

4.3.基于日期和时间的滚动

Using the policies offered by Log4j2, we’ll set up an appender to roll and compress the log file based on time:

使用Log4j2提供的策略,我们将设置一个appender,根据时间滚动和压缩日志文件。

<RollingFile name="roll-by-time" 
  fileName="target/log4j2/roll-by-time/app.log"
  filePattern="target/log4j2/roll-by-time/app.%d{MM-dd-yyyy-HH-mm}.log.gz"
  ignoreExceptions="false">
    <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
    </PatternLayout>
    <TimeBasedTriggeringPolicy />
</RollingFile>

The key here is the TimeBasedTriggeringPolicy, which allows us to use time-related placeholders in the template of the rolled file names. Note that, since we need only a single triggering policy, we don’t have to use the Policies tag, like in the previous example.

这里的关键是TimeBasedTriggeringPolicy,它允许我们在滚动文件名的模板中使用与时间相关的占位符。注意,由于我们只需要一个触发策略,所以我们不必像前面的例子那样使用Policies标签。

4.4. Rolling Based on Size and Time

4.4.基于规模和时间的滚动

As previously described, a more compelling scenario is to roll and compress log files based on both time and size. Here’s an example of how we can set up Log4j2 for this task:

如前所述,一个更有说服力的方案是根据时间和大小来滚动和压缩日志文件。下面是一个例子,说明我们如何为这项任务设置Log4j2。

<RollingFile name="roll-by-time-and-size" 
  fileName="target/log4j2/roll-by-time-and-size/app.log"
  filePattern="target/log4j2/roll-by-time-and-size/app.%d{MM-dd-yyyy-HH-mm}.%i.log.gz" 
  ignoreExceptions="false">
    <PatternLayout>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
    </PatternLayout>
    <Policies>
        <OnStartupTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="5 KB" />
        <TimeBasedTriggeringPolicy />
    </Policies>
    <DefaultRolloverStrategy>
        <Delete basePath="${baseDir}" maxDepth="2">
            <IfFileName glob="target/log4j2/roll-by-time-and-size/app.*.log.gz" />
            <IfLastModified age="20d" />
        </Delete>
    </DefaultRolloverStrategy>
</RollingFile>

With this configuration, we stated that a roll should occur based on time and size. The appender is able to understand what time interval we’re referring to because of the pattern used for the file name, “app.%d{MM-dd-yyyy-HH-mm}.%i.log.gz”, which implicitly sets a roll to occur every minute and compress the rolled file.

有了这个配置,我们说应该根据时间和大小来发生滚动。附加器能够理解我们所指的时间间隔,因为文件名使用的模式是”app.%d{MM-dd-yyy-HH-mm}.%i.log.gz”,它隐含地设置每分钟发生一次滚动,并压缩滚动的文件。

We also added a DefaultRolloverStrategy to delete old rolled files matching certain criteria. We configured ours to delete files that match the given pattern when they’re older than 20 days.

我们还添加了一个DefaultRolloverStrategy,以删除符合某些标准的旧的滚动文件。我们配置了我们的策略,当文件超过20天时,删除符合给定模式的文件。

4.5. Maven Dependencies

4.5.Maven的依赖性

To use Log4j2 as our preferred logging library, we need to update our project’s POM with the following dependency:

为了使用Log4j2作为我们的首选日志库,我们需要更新我们项目的POM,加入以下依赖关系。

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>

As usual, we can find the latest version on Maven Central.

像往常一样,我们可以在Maven中心找到最新的版本

5. Rolling File Appenders in Slf4j

5.Slf4j中的滚动文件应用程序

5.1. Maven Dependencies

5.1.Maven的依赖性

When we want to use Slf4j2 with a Logback backend as our logging library, we’ll add this dependency to our pom.xml:

当我们想使用Slf4j2与Logback后端作为我们的日志库时,我们将把这个依赖关系添加到我们的pom.xml

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.6</version>
</dependency>

As usual, we can find the latest version on Maven Central.

像往常一样,我们可以在Maven中心找到最新的版本

5.2. Rolling Based on File Size

5.2.基于文件大小的滚动

Now let’s see how to use Slf4j with its default back-end Logback. We’ll set up file rolling in the configuration file, logback.xml, which is placed in the application’s classpath:

现在让我们看看如何使用Slf4j的默认后端Logback。我们将在配置文件logback.xml中设置文件滚动,该文件被放在应用程序的classpath中。

<appender name="roll-by-size" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>target/slf4j/roll-by-size/app.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
        <fileNamePattern>target/slf4j/roll-by-size/app.%i.log.zip</fileNamePattern>
        <minIndex>1</minIndex>
        <maxIndex>3</maxIndex>
        <totalSizeCap>1MB</totalSizeCap>
    </rollingPolicy>
    <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
       <maxFileSize>5KB</maxFileSize>
    </triggeringPolicy>
    <encoder>
        <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
</appender>

Again we encounter the concept of rolling policy. The basic mechanism is the same as that used by Log4j and Log4j2. The FixedWindowRollingPolicy allows us to use an index placeholder in the name pattern of the rolled file.

我们再次遇到了滚动策略的概念。其基本机制与Log4j和Log4j2使用的机制相同。FixedWindowRollingPolicy允许我们在滚动文件的名称模式中使用一个索引占位符。

When the size of the log file grows over the configured limit, a new file is allocated. The old content is stored as the first file on the list, shifting the existing ones one place further.

当日志文件的大小增长超过配置的限制时,就会分配一个新的文件。旧的内容被存储为列表中的第一个文件,将现有的文件再移开一个位置。

5.3. Rolling Based on Time

5.3.基于时间的滚动

In Slf4j, we can roll a log file based on time using the provided TimeBasedRollingPolicy. This policy allows us to specify the template name of the rolling file using time and date related placeholders:

在Slf4j中,我们可以使用提供的TimeBasedRollingPolicy,根据时间滚动日志文件。这个策略允许我们使用时间和日期相关的占位符来指定滚动文件的模板名称。

<appender name="roll-by-time" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>target/slf4j/roll-by-time/app.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>target/slf4j/roll-by-time/app.%d{yyyy-MM-dd-HH-mm}.log.zip
        </fileNamePattern>
        <maxHistory>20</maxHistory>
        <totalSizeCap>1MB</totalSizeCap>
    </rollingPolicy>
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
    </encoder>
</appender>

5.4. Rolling Based on Size and Time

5.4.基于规模和时间的滚动

If we need to roll a file based on both time and size, we can use the provided SizeAndTimeBasedRollingPolicy. When using this policy, we must specify both a time-related placeholder and an index placeholder.

如果我们需要根据时间和大小来滚动文件,我们可以使用提供的SizeAndTimeBasedRollingPolicy。当使用这个策略时,我们必须同时指定一个与时间有关的占位符和一个索引占位符。

Each time the size of the log file for a certain time interval grows beyond the configured size limit, another log file with the same value for the time-related placeholder, but with an incremented index, is created:

每当某个时间间隔的日志文件的大小增长超过配置的大小限制时,就会创建另一个与时间相关的占位符数值相同的日志文件,但索引会增加。

<appender name="roll-by-time-and-size"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>target/slf4j/roll-by-time-and-size/app.log</file>
    <rollingPolicy
      class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
        <fileNamePattern>
            target/slf4j/roll-by-time-and-size/app.%d{yyyy-MM-dd-mm}.%i.log.zip
        </fileNamePattern>
        <maxFileSize>5KB</maxFileSize>
        <maxHistory>20</maxHistory>
        <totalSizeCap>1MB</totalSizeCap>
    </rollingPolicy>
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</pattern>
    </encoder>
</appender>

6. Conclusion

6.结论

In this article, we learned that leveraging a logging library to roll the files saves us the burden of managing the log files manually. Instead, we can focus on the development of our business logic. Rolling file appenders are a valuable tool that should be in every developer’s toolbox.

在这篇文章中,我们了解到,利用日志库来滚动文件,可以节省我们手动管理日志文件的负担。相反,我们可以专注于业务逻辑的开发。滚动文件应用程序是一个有价值的工具,应该放在每个开发者的工具箱里。

As usual, the sources are available on GitHub, where the example applications presented in this article are configured to log using several different rolling setups in order to allow us to find a good base configuration to be further tweaked to suit our needs.

像往常一样,源代码可在GitHub上获得,本文介绍的示例应用程序被配置为使用几种不同的滚动设置进行记录,以便让我们找到一个良好的基础配置,并进一步调整以适应我们的需求。