done is better than perfect

自分が学んだことや、作成したプログラムの記事を書きます。すべての記載は他に定める場合を除き個人的なものです。

Log4jのDailyRollingFileAppenderはrollOverするタイミングでプロセスが実行していなくても、次にプロセスが実行されるタイミングでrollOverする話

自分用メモ

DailyRollingFileAppenderで、日付でのローテーションを行う設定をする場合、普段ローテーションするタイミングで サーバーなりプロセスなりが落ちていた場合どうするのでしょう。

まずは確認。DRFAだと普段はMidnightにローテーションされる

 At midnight, on March 8th, 2002, /foo/bar.log will be copied to /foo/bar.log.2002-03-08. Logging for the 9th day of March will be output to /foo/bar.log until it is rolled over the next day.

DailyRollingFileAppender (Apache Log4j 1.2.17 API)

じゃあMidnightにサーバー落ちてたらどうなるのっと。

その答えは以下

log4j/DailyRollingFileAppender.java at v1_2-branch · apache/log4j · GitHub

  /**
   * This method differentiates DailyRollingFileAppender from its
   * super class.
   *
   * <p>Before actually logging, this method will check whether it is
   * time to do a rollover. If it is, it will schedule the next
   * rollover time and then rollover.
   * */
  protected void subAppend(LoggingEvent event) {
    long n = System.currentTimeMillis();
    if (n >= nextCheck) {
      now.setTime(n);
      nextCheck = rc.getNextCheckMillis(now);
      try {
    rollOver();
      }
      catch(IOException ioe) {
    LogLog.error("rollOver() failed.", ioe);
      }
    }
    super.subAppend(event);
   }
}

つまり、まずファイルにログを書き出しする前にちゃんとローテーションされているかをチェックして、されていなければrollOverしてくれるっぽい