​

如果任由访问日志写下去,日志文件会变得越来越大,甚至是写满磁盘。

所以,我们需要想办法把日志做切割,比如每天生成一个新的日志,旧的日志按规定时间删除即可。

实现日志切割可以通过写shell脚本或者系统的日志切割机制实现。


shell脚本切割Nginx日志


切割脚本内容: #!/bin/bash logdir=/var/log/nginx #定义日志路径 prefix=`date -d "-1 day" +%y%m%d` #定义切割后的日志前缀 cd $logdir  for f in `ls access.log` do mv $f $f-$prefix #把日志改名 done /bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null #生成新的日志 bzip2 *$prefix #压缩日志 find . -type f -mtime +180 |xargs /bin/rm -f #删除超过180天的老日志


示例:


#!/bin/bash logdir=/usr/local/nginx/logs/ prefix=`date -d "-1 day" +%y%m%d` cd $logdir for f in `ls access.log` do mv $f $prefix-$f done /bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null find . -type f -mtime +180 |xargs /bin/rm -f



系统日志切割机制


在/etc/logrotate.d/下创建nginx文件,内容为: /data/logs/access.log { daily rotate 30 missingok notifempty compress sharedscripts postrotate /bin/kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid 2>/dev/null) 2>/dev/null || : endscript }  说明:   nginx日志在/data/logs/目录下面,日志名字以log结尾   daily表示每天切割   rotate 30表示日志保留30天   missingok表示忽略错误   notifempty表示如果日志为空,不切割   compress表示压缩   sharedscripts和endscript中间可以引用系统的命令   postrotate表示当切割之后要执行的命令


附:

1.如何测试logrotate程序执行的情况

答:/usr/sbin/logrotate -d /etc/logrotate.d/nginx

2.怎么查看log文件的具体执行情况

答:cat /var/lib/logrotate/status

3.使用-v或-d参数时,显示log does not need rotating

答:logrotate在对status未记录的文件进行转储时,会在status添加一条该文件的记录,并将操作时间设为当天。之后程序再次对此文件进行转储时发现这个文件今天已经操作过,就不再进行相关操作。

解决方法:

1. vi /var/lib/logrotate/status 更改相对应的文件操作日期

2. 使用-s指定状态文件

3.分割日志时报错:error: skipping "/var/log/nginx/test.access.log" because parent directory has insecure permissions (It's world writable or writable by group which is not "root") Set "su" directive in config file to tell logrotate which user/group should be used for rotation.

答:添加“su root list”到/etc/logrotate.d/nginx文件中即可

如下:

/var/log/nginx/*.log {

su root list

daily

missingok

rotate 52

compress

delaycompress

notifempty

#ifempty

create 0640 www-data adm

sharedscripts

postrotate

[ ! -f /var/run/nginx.pid ] || kill -USR1 `cat /var/run/nginx.pid`

endscript

}