nginx logrotate 配置

nginx logrotate 配置

轮换 nginx 日志文件的最佳方法是什么?在我看来,我应该在 /etc/logrotate.d/ 中创建一个文件“nginx”,并用以下代码填充它,然后执行 /etc/init.d/syslog 重新启动。

这是我的配置(我还没有测试过):

 /usr/local/nginx/logs/*.log {
    #rotate the logfile(s) daily
    daily
    # adds extension like YYYYMMDD instead of simply adding a number
    dateext
    # If log file is missing, go on to next one without issuing an error msg
    missingok
    # Save logfiles for the last 49 days
    rotate 49
    # Old versions of log files are compressed with gzip
    compress
    # Postpone compression of the previous log file to the next rotation cycle
    delaycompress
    # Do not rotate the log if it is empty
    notifempty
    # create mode owner group
    create 644 nginx nginx
    #after logfile is rotated and nginx.pid exists, send the USR1 signal
    postrotate
       [ ! -f /usr/local/nginx/logs/nginx.pid ] || kill -USR1 `cat
       /usr/local/nginx/logs/nginx.pid`
    endscript
 }

我在 /usr/local/nginx/logs/ 中同时拥有 access.log 和 error.log 文件,并且希望每天轮换这两个文件。有人能告诉我“dateext”是否正确吗?我希望日志文件名类似于“access.log-2010-12-04”。还有一件事:我可以在每天的特定时间(例如晚上 11 点)轮换日志吗?如果可以,怎么做?谢谢。

答案1

man logrotate

   dateformat format_string
          Specify  the  extension for dateext using the notation similar to strftime(3) function. Only %Y %m
          %d and %s specifiers are allowed.  The default value is -%Y%m%d. Note that also the character sep‐
          arating log name from the extension is part of the dateformat string. The system clock must be set
          past Sep 9th 2001 for %s to work correctly.  Note that the datestamps  generated  by  this  format
          must be lexically sortable (i.e., first the year, then the month then the day. e.g., 2001/12/01 is
          ok, but 01/12/2001 is not, since 01/11/2002 would sort lower while it is later).  This is  because
          when using the rotate option, logrotate sorts all rotated filenames to find out which logfiles are
          older and should be removed.

有人能告诉我“dateext”是否正确吗?我希望日志文件名类似于“access.log-2010-12-04”。

在您的配置文件中插入一条dateformat指令,如下所示:

 /usr/local/nginx/logs/*.log {
    daily
    dateext
    dateformat -%Y-%m-%d
    ...

还有一件事:我可以在每天的特定时间(例如晚上 11 点)进行日志轮换吗?

默认情况下,logrotate 在凌晨 4 点通过 cron 运行:

/etc/cron.daily/logrotate

#!/bin/sh

/usr/sbin/logrotate /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

您可以将此文件移动到某个地方并重命名为logrotate.sh,然后创建一个新文件,/etc/cron.d/如下所示:

0 23 * * * root /path/to/logrotate.sh

答案2

您可以一次旋转所有虚拟主机:

/var/www/vhosts/*/logs/*.log { ... }

答案3

的值dateext由指令给出dateformat,默认为%Y%m%d(年、月、日)。您可以像 一样自定义它%Y-%m-%d

如果您已经logrotate安装并运行,它很可能每天都在运行cron,您只需找到它来更改时间(请记住其他因素也会影响它,例如是否使用anacron,但每个系统都不同)。

相关内容