滚动日志文件而不会丢失任何日志事件

Moh*_*ani 1 logging gzip log-rotation

我有一个 8GB 的​​文件,调用php.log了一个正在运行的 php 脚本登录到它。记录每个事件对我来说很重要,我想压缩它并清空当前文件而不停止 Web 服务器。

如果我运行:

    mv php.log php.log.backup20140305-01
    touch php.log
Run Code Online (Sandbox Code Playgroud)

我会丢失一些数据。如何在不丢失任何数据的情况下执行此操作?

Flu*_*lup 5

您会发现配置logrotate为您进行轮换更容易。如果您创建一个/etc/logrotate.d/php包含以下内容的名为的文件,它将自动处理日志轮换。这只是一个指南,因此请确保在将其投入生产之前对其进行测试和自定义。

/path/to/php.log {
    daily  
    missingok              # don't rotate if the file isn't there...
    notifempty             # ...or if it's zero-length
    rotate 30              # keep 30 days' worth of logs
    compress               # gzip the logs, but...
    delaycompress          # ...only after they're over a day old
    create 640 root adm    # permissions with which to create new files
    sharedscripts
    postrotate
        /etc/init.d/apache2 graceful    # or whatever makes your process let go of the log file
    endscript
}
Run Code Online (Sandbox Code Playgroud)

注意:此提取中断logrotate语法中的注释,因此请确保将它们从您的实时配置文件中删除。