如何根据时间或大小配置回滚到翻转,文件总数绝对最大?

时间:2014-03-11 17:30:38

标签: java logback

道歉,如果这被视为重复。 This question非常相似但不一样。我对控制文件的总数感兴趣(实际上我想控制所有日志的总大小)。

我希望以下内容退回:

  • 对于当前文件,每12小时翻转一次,或文件达到100MB。
  • 无论如何,总共不要使用超过600MB的空间(我也可以这样说:没有超过5个备份文件)。

第一点似乎很容易。我知道TimeBasedRollingPolicy,我知道我可以限制每个文件的大小,但这还不够。我需要一种方法来限制日志文件的数量,而不仅仅是时间段的总数。

1 个答案:

答案 0 :(得分:3)

已经很长时间了,有人要求提供代码,所以我想我会将其作为答案发布。我还没有测试过它,但它应该是一个合理的例子。

/**
 * Extends SizeBasedTriggeringPolicy to trigger based on size or time in minutes
 *
 * Example:
 *   <triggeringPolicy class="com.foo.bar.TimeSizeBasedTriggeringPolicy">
 *       <MaxFileSize>10MB</MaxFileSize>
 *       <RolloverInMinutes>35</RolloverInMinutes>
 *   </triggeringPolicy>
 *
 * This would rollover every 35min or 10MB, whichever comes first. Because isTriggeringEvent()
 * is only called when a log line comes in, these limits will not be obeyed perfectly.
 */
public class TimeSizeBasedTriggeringPolicy<E> extends SizeBasedTriggeringPolicy<E> {
     private long MILLIS_IN_A_MINUTE = 60 * 1000;

     private long rolloverPeriod;
     private long nextRolloverTime;

     @Override
     public void start() {
         nextRolloverTime = System.currentTimeMillis() + rolloverPeriod;
         super.start();
     }

     @Override
     public boolean isTriggeringEvent(File activeFile, final E event) {
         long currentTime = System.currentTimeMillis();
         boolean isRolloverTime = super.isTriggeringEvent(activeFile, event) ||
                 currentTime >= nextRolloverTime;

         // Reset the rollover period regardless of why we're rolling over.
         if (isRolloverTime) {
             nextRolloverTime = currentTime + rolloverPeriod;
         }

         return isRolloverTime;
     }

     public long getRolloverInMinutes() {
         return rolloverPeriod / MILLIS_IN_A_MINUTE;
     }

     public void setRolloverInMinutes(long rolloverPeriodInMinutes) {
         this.rolloverPeriod = rolloverPeriodInMinutes * MILLIS_IN_A_MINUTE;
     }
 }