轮换始终处于打开状态且正在写入的文件

轮换始终处于打开状态且正在写入的文件

我有一个 Linux 应用程序,它会不断将日志信息写入日志文件,例如。/var/log/application.log由于应用程序不会自动轮换文件,因此该日志文件在几周内可能会达到 GB 的大小,因此我希望能够正确轮换此文件

我主要关心的是,为了旋转应用程序始终打开的文件,我可能需要:

  1. 将文件移动到其旋转形式/var/log/application.log -> /var/log/application.log.2013-01-28

  2. 创建一个空的/var/log/application.log注意:目前申请流程仍在进行中/var/log/application.log.2013-01-28

  3. 更改应用程序进程的文件描述符,使其再次指向/var/log/application.log

那么,我是对的吗?如果是这样,我该怎么做?(主要是更改文件描述符部分)

如果不是,那么正确的方法是什么以及该如何做?

答案1

编写一个logrotate配置以供使用copytruncate

copytruncate
    Truncate the original log file 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.

答案2

大多数此类应用程序都会对信号(例如SIGHUP)做出响应,并在收到信号后关闭并重新打开其日志文件。请查看应用程序的文档以了解要发送的正确信号。

相关内容