Nginx日志切割方法

方法1:使用自定义脚本

方法1优点:可精确定义切割时间,切割后的日志里只包含相应时段的内容,便于查阅管理。如access.log-20210816只包含20210816的日志内容。

脚本内容如下:

cat nginx_log_rotate.sh

#!/bin/bash

DATE=`date -d “-1 day” +%Y%m%d`

LOGDIR=”/app/nginx/log/”

NGINX_PID=”/app/nginx/run/nginx.pid”

cd $LOGDIR

for log in `find . -name “*.log”`

do

 mv $log $log-$DATE

done

/bin/kill -USR1 `cat $NGINX_PID`

find . -name “*.log-*” -mtime +30 | xargs rm -f

设置定时任务:

# crontab -e

0 0 * * * /bin/bash /app/ops/nginx_log_rotate.sh >/dev/null 2>&1

经上述设置后,每天0点对/app/nginx/log/目录的下*.log日志文件进行切割,并保留30天内的切割日志。

说明:若需要按小时切割日志,DATE设置为date -d “-1 hour” +%Y%m%d%H并调整crontab定时任务。

方法2:使用logrotate

方法2优点:不需要写脚本。

方法2缺点:默认的logrotate会在每天的3点05分到3点50分之间执行日志切割,这样日志内容与日志文件名时间对应不上,不便于日志查阅管理。即使自定义logrotate执行时间,具体切割的时间也不固定,下面会详细说明。

说明:自定义logrotate执行时间时,不能直接在/etc/logrotate.d目录下新建配置文件。可以/etc/logrotate.d目录下新建子目录,并在子目录中新建配置文件。

操作步骤如下:

1./etc/logrotate.d/下新建nginxlogrotate目录:

mkdir -p /etc/logrotate.d/nginxlogrotate

2.nginxlogrotate目录下创建nginx日志切割配置文件:

cd /etc/logrotate.d/nginxlogrotate

vim nginx

内容如下:

/app/nginx/log/*.log

{

su root root

daily

rotate 30

missingok

notifempty

dateext

create 0644 yun yun

sharedscripts

postrotate

  /bin/kill -USR1 `cat /app/nginx/run/nginx.pid 2>/dev/null` 2>/dev/null || true

endscript

}

保存并退出。

部分参数说明:

su root root添加此行参数是为了避免因日志所在目录权限设置不当而导致不能切割日志

daily每天切割日志

rotate 30 保留30个切割日志文件

notifempty当日志文件为空时,不进行切割

dateext 切割日志文件后面加-yyyymmdd

create 0644 yun yun 指定创建新文件的属性

3.添加定时任务:crontab -e

59 23 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginxlogrotate/nginx >/dev/null 2>&1

4.测试配置文件:/usr/sbin/logrotate -vfd /etc/logrotate.d/nginxlogrotate/nginx 经上述设置后,按理应该每天23:59对/app/nginx/log/目录的下*.log日志文件进行切割,并保留30天内的切割日志。但实际日志切割时间不一定是23:59,但会在23:00-24:00之间。