在进程仍在运行时轮换日志文件

在进程仍在运行时轮换日志文件

我正在运行一个进程,它将标准输出和标准错误写入日志文件/var/log/dragonturtle.log。是否有办法轮换日志文件,并让进程继续写入新的日志文件而不终止进程?

当前发生了什么(给出下面的 logrotate 配置):

  • 进程写入/var/log/dragonturtle.log
  • Logrotate 移动/var/log/dragonturtle.log/var/log/dragonturtle.log.1
  • 进程继续写入/var/log/dragonturtle.log.1

我希望发生什么:

  • 进程写入/var/log/dragonturtle.log
  • Logrotate 副本/var/log/dragonturtle.log/var/log/dragonturtle.log.1
  • 对数旋转截断/var/log/dragonturtle.log
  • 进程继续写入/var/log/dragonturtle.log

/etc/logrotate.d/dragonturtle:

/var/log/dragonturtle.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 644 dragonturtle dragonturtle
}

答案1

logrotate执行您所描述的操作的选项是copytruncate.只需将此选项添加到现有的 logrotate 配置中即可。以下是 logrotate.conf 手册的摘录:

   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 can not 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  log-
          ging  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

请注意,在 logrotate conf 文件中使用 copytruncate 选项时,可能会丢失一些日志行,因为截断旧文件并告诉进程写入同一文件时会出现一小段时间延迟。它不适合某些每隔毫秒写入日志的应用程序。

相关内容