11

语境:

我想使用 log4j 将与审计相关的日志写入特定的日志文件,比如 audit.log。我不想使用 syslogappender(基于 udp),因为我不想容忍数据丢失。另外,当文件达到一定大小时,我正在使用 logrotate 来轮换 audit.log。

问题:

我遇到的是,当 logrotate 将文件 audit.log 旋转到 audit.log.1 时,log4j 继续写入 audit.log.1 而不是写入 audit.log。

可能的方法:

  1. 我知道我可以使用 rollingfileappender 进行日志轮换,而不是使用 logrotate,所以当 rollingfileappender 滚动文件时,它会毫不费力地切换到新文件。但是我不能使用 rollingfileappender 的原因是我想使用 logrotate 的 post rotate 功能在旋转发生后触发一些rollingfileappender 无法提供的脚本。

  2. 我能想到的另一种绝望的方法是自己编写一个 log4j 自定义的 appender 来关闭日志文件(audit.log.1)并在检测到文件被轮换时打开新的(audit.log)。

  3. 我从未使用过 ExternallyRolledFileAppender,但如果可以使用 logrotate post rotate 将信号发送到 ExternallyRolledFileAppender 并使 log4j 知道文件已旋转,并开始写入新文件?

问题:

只是想知道是否已经发明/编写了一些像这样的附加程序?还是我有其他选择来解决这个问题?

4

1 回答 1

6

查看logrotatecopytruncate选项,它可能对您的情况有所帮助:

copytruncate
       Truncate the original log file to zero size  in  place
       after  creating  a copy, instead of moving the old log 
       file and optionally creating a new  one.   It  can  be  
       used  when  some  program  cannot be told to close its 
       logfile and thus might continue writing (appending) to
       the  previous  log file forever.  Note that there is a
       very small time slice between  copying  the  file  and 
       truncating  it,  so  some  logging data might be lost.
       When this option is used, the create option will  have
       no effect, as the old log file stays in place
于 2012-05-24T12:58:09.163 回答