2010-11-02 56 views
3

Log4j RollingFileAppender的正常行爲是在第一個日誌消息發生在不同日期時滾動,但即使沒有任何事件發生,但某些日誌文件對於每個日期都會變得溫暖和模糊。有沒有辦法強制它在午夜後滾動而不寫虛擬消息到日誌?乾淨地強制Log4j RollingFileAppender在午夜後不久滾動?

+2

我的猜測是,這是不是默認的行爲,因爲這需要某種形式的計時器線程,其中將要求您的應用程序在後臺運行不斷運行。這不是log4j強加的限制。 – Pace 2010-11-02 23:09:38

回答

4

我已經仔細查看了這段代碼 - 簡單的答案是'不'。翻轉是作爲Appender上的doAppend()流的一部分觸發的 - 觸發它的唯一方法是記錄一些內容。

你可以用cron來僞造這個:只需要一個cron腳本在明天11:58就可以觸摸這個文件。這會讓你找到你正在尋找的空白日誌文件行爲。

下面是實現翻轉功能代碼:

void rollOver() throws IOException { 

    /* Compute filename, but only if datePattern is specified */ 
    if (datePattern == null) { 
     errorHandler.error("Missing DatePattern option in rollOver()."); 
     return; 
    } 

    String datedFilename = fileName+sdf.format(now); 
    // It is too early to roll over because we are still within the 
    // bounds of the current interval. Rollover will occur once the 
    // next interval is reached. 
    if (scheduledFilename.equals(datedFilename)) { 
     return; 
    } 

    // close current file, and rename it to datedFilename 
    this.closeFile(); 

    File target = new File(scheduledFilename); 
    if (target.exists()) { 
     target.delete(); 
    } 

    File file = new File(fileName); 
    boolean result = file.renameTo(target); 
    if(result) { 
     LogLog.debug(fileName +" -> "+ scheduledFilename); 
    } else { 
     LogLog.error("Failed to rename ["+fileName+"] to ["+scheduledFilename+"]."); 
    } 

    try { 
     // This will also close the file. This is OK since multiple 
     // close operations are safe. 
     this.setFile(fileName, false, this.bufferedIO, this.bufferSize); 
    } 
    catch(IOException e) { 
     errorHandler.error("setFile("+fileName+", false) call failed."); 
    } 
    scheduledFilename = datedFilename; 
    } 
+2

如果您可以訪問appender,也可以調用RollingFileAppender.rollOver。 – 2010-11-09 14:14:36

+0

當日志不存在時調用rollover()將不會得到提交者所需的內容:正確日期和時間的空日誌文件。 – 2010-11-10 01:38:54