默认情况下,logback 不为此类功能提供滚动策略实现。您可以为此创建自己的滚动策略触发器,方法是扩展 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();
}
}
在 logback 配置中的 appender 中使用的滚动策略:
<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>