Spring Boot logback.xml中的回滚策略-x小时后回滚文件

gcuhipw9  于 2023-02-04  发布在  Spring
关注(0)|答案(1)|浏览(230)
<rollingPolicy 
 class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover hourly -->
<fileNamePattern>${DEV_HOME}/archived/server.%d{yyyy-MM-dd_HH}.log
</fileNamePattern>
</rollingPolicy>

我现在使用这种方法每小时滚动,但需要改变这在8小时滚动{即,我们有24小时,然后3个文件将创建8小时的日志值每个}。
有什么解决办法吗?

mec1mxoz

mec1mxoz1#

默认情况下,回登录不为此类功能提供滚动策略实现。您可以为此创建自己的滚动策略触发器,方法是扩展DefaultTimeBasedFileNamingAndTriggeringPolicy并重写computeNextCheck方法,以便在从文件名模式推断的滚动时间段的指定倍数之后执行下一次滚动。
自定义滚动触发器策略类:

import ch.qos.logback.core.joran.spi.NoAutoStart;
import ch.qos.logback.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy;

@NoAutoStart // @NoAutoStart prevents null pointer exception by stopping Joran from launching the start method before initialization
public class ArbitraryTimeRollingTriggerPolicy<E> extends DefaultTimeBasedFileNamingAndTriggeringPolicy<E> {
    // Setters and getters are required to set times inside logback configuration xml file
    private int times;
    
    public int getTimes() {
        return times;
    }

    public void setTimes(int times) {
        this.times = times;
    }

    @Override
    protected void computeNextCheck() {
        nextCheck = rc.getEndOfNextNthPeriod(dateInCurrentPeriod, times).getTime();
    }
}

回登录配置中要在附加器内使用的滚动策略:

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
    <fileNamePattern>${DEV_HOME}/archived/server.%d{yyyy-MM-dd_HH}.log</fileNamePattern>
    <!-- Custom Rolling Trigger Policy -->
    <timeBasedFileNamingAndTriggeringPolicy class="<YOUR-PACKAGE>.ArbitraryTimeRollingTriggerPolicy">
        <!-- Number of hours, after which you want to rotate the file -->
        <times>8</times>
    </timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>

相关问题