How can logback be configured to automatically delete log files?

To configure Logback to automatically delete logs, you can use either Logback’s RollingFileAppender or TimeBasedRollingPolicy. Here are examples of both configurations.

Configure using RollingFileAppender:

<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/path/to/logfile.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>/path/to/logfile.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>30</maxHistory> <!-- 设置保存历史日志文件的最大数量 -->
    </rollingPolicy>
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

Configure with TimeBasedRollingPolicy.

<appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/path/to/logfile.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>/path/to/logfile.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>30</maxHistory> <!-- 设置保存历史日志文件的最大数量 -->
    </rollingPolicy>
    <encoder>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

These settings will generate a new log file every day and keep the most recent 30 days of log files. You can adjust the values of fileNamePattern and maxHistory as needed.

广告
Closing in 10 seconds
bannerAds