旋转始终打开并正在写入的文件

Bru*_*aco 12 linux filesystems log-files process rotation

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

我在这里主要担心的是,要始终旋转由应用程序打开的文件,我可能需要:

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

  2. 创建一个空的/var/log/application.log. obs:此时申请进程还在写入/var/log/application.log.2013-01-28

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

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

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

R. *_* S. 13

编写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.
Run Code Online (Sandbox Code Playgroud)