Linux 上由自由空间驱动的日志轮换吗?

Linux 上由自由空间驱动的日志轮换吗?

有人刚刚问我“我们应该将应用程序的日志保留多长时间”,我的回答是“直到磁盘满了”,因为除了空间不足之外没有其他理由将它们扔掉。

但是,标准 logrotate 要求我们指定特定的周期 + 轮换次数。是否有类似的东西可以让我们说“每天轮换,并保留尽可能多的历史记录,直到只剩下 5% 的可用空间”?

平台是Redhat Linux。

答案1

您或许可以使用 firstaction 或 lastaction 指令来调用测试磁盘可用空间的 shell 脚本,然后对最旧的文件运行删除操作。

   firstaction/endscript
          The lines between firstaction and endscript (both of which must appear on lines by themselves) are
          executed (using /bin/sh) once before all log files that match the wildcarded pattern are  rotated,
          before  prerotate  script  is  run  and  only if at least one log will actually be rotated.  These
          directives may only appear inside a log file definition. Whole pattern is passed to the script  as
          first  argument.  If  the script exits with error, no further processing is done. See also lastac-
          tion.

更新:

以下是有关您可以运行的脚本类型的 Stackoverflow 帖子:

https://stackoverflow.com/questions/7523059/remove-oldest-file-in-repository

答案2

logrotate 本身没有这样的选项。您可以添加一个 cron 脚本,当可用空间低于您的标准时,它会查找最旧的日志并将其删除。您也可以进行其他验证。但是,磁盘一直太满并不是一个好主意,因为系统将无法创建大型临时文件,并可能导致应用程序失败。

答案3

我只是想指出,在某些情况下,您不希望日志填满所有可用磁盘空间。我处理过几台具有精简配置 /var 目录的主机,将日志保持在一定大小至关重要。我们使用 cronies 作业与 logrorate 结合使用来降低大小。您可以在您的环境中使用类似的东西,尽管像 splunk 或 syslog-ng 这样的中央日志服务器可能是更好的选择。

答案4

正如@cjc所建议的,您可以使用firstaction。 请参阅以下示例:

/mnt/user/logs/*.log  /mnt/user/logs/*/*.log {
        daily
        missingok
        rotate 7
        compress
        delaycompress
        notifempty
        su root www-data
        create 760 root www-data
        firstaction
          for file in `find  -type f -size +1024M`; do
              percent=`df -h | grep /mnt/user | awk '{print $5}' | sed 's/%//'`
              if [ $percent -gt 50 ]; then 
                  echo "Removed $file" >> /mnt/user/logs/logrotate.log
                  rm $file
              fi
           done;
        endscript
}

在此示例中,您删除了大于1GB来自/mnt/用户如果分区使用的空间大于50%

相关内容