Log4j FileAppender 重新创建已删除的文件

ras*_*dov 5 java log4j fileappender

我在我正在从事的项目中使用 Log4j 作为日志记录框架。我有以下情况:Log4j 配置为将日志写入日志文件。在某些时候,该日志文件会被复制到另一个目标并被删除。日志框架继续工作,但日志未写入日志文件,因为它已被删除。有没有办法告诉 Log4j 重新创建文件并继续将日志写入日志文件。

最好的问候,拉希德

小智 1

我研究了log4j的源码,发现log4j无法创建新的日志文件,它只是在删除日志文件时将错误消息打印到system.err

    /** 
     This method determines if there is a sense in attempting to append. 

     <p>It checks whether there is a set output target and also if 
     there is a set layout. If these checks fail, then the boolean 
     value <code>false</code> is returned. */  

  protected   boolean checkEntryConditions() {  
    if(this.closed) {  
      LogLog.warn("Not allowed to write to a closed appender.");  
      return false;  
    }  

    if(this.qw == null) {  
      errorHandler.error("No output stream or file set for the appender named ["+  
            name+"].");  
      return false;  
    }  

    if(this.layout == null) {  
      errorHandler.error("No layout set for the appender named ["+ name+"].");  
      return false;  
    }  
    return true;  
  }  
Run Code Online (Sandbox Code Playgroud)

我认为有两种解决方法

  1. 创建另一个 cron 线程来监视日志文件
  2. 在getLog或getInstance(singleton)中添加判断,检查日志文件是否存在,如果不存在则init log4j