当logrotate旋转日志文件时,log4j fileappender不会切换到新文件

She*_*jie 11 log4j logrotate rollingfileappender fileappender log-rotation

语境:

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

问题:

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

可能的方法:

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

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

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

题:

只是想知道是否有一些像已经发明/写的那样的追加者?或者我还有其他选择来解决这个问题吗?

hol*_*eek 5

检查出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
Run Code Online (Sandbox Code Playgroud)