Nginx做为HTTP服务器,天天记录的日志不少,若是不善加管理,没用多久就会把磁盘充满。Apache有rotatelogs程序帮助轮替,而Nginx没有。好在咱们的Linux带了logrotate程序帮助咱们完成这个任务。nginx
操做系统:CentOS 6.6 x64 ( Linux 2.6.32-431.23.3.el6.x86_64 )
shell
logrotate版本:3.7.8-17.el6.x86_64
vim
Nginx版本:nginx/1.6.2
服务器
logrotate是一款专门用来管理日志轮替的程序,各大Linux发行版在安装的时候就已经内置了此程序。ide
使用方法:post
logrotate [OPTION...] <configfile> -d, --debug 测试,但不会真正运行(已包含-v选项) -f, --force 强制对文件轮替 -m, --mail=command 后接参数,参数是发邮件命令(替代`/bin/mail`) -s, --state=statefile 状态文件的路径 -v, --verbose 输出轮替过程当中的信息到标准输出
建立/etc/logrotate.d/nginx
配置文件,写入配置。这里咱们nginx日志是位于/data/logs/nginx_access.log
和/data/logs/nginx_error.log
。测试
shell$ sudo vim /etc/logrotate.d/nginx /data/logs/nginx_access.log /data/logs/nginx_error.log { missingok #若是日志文件不存在,则不报错,直接忽略 notifempty #若是日志文件为空则不执行轮替操做 daily #频次为天天运行 rotate 30 #保留30天的日志 sharedscripts #日志共享脚本,也就是说等access和error两个日志都rotate以后再执行下面的脚本 postrotate #设置脚本在rotate以后执行,对应的有一个选项是prerotate if [ -f /service/nginx/logs/nginx.pid ]; then #设置rotate以后nginx需从新载入配置文件,不然nginx不会将日志写入新的日志文件中 /service/nginx/sbin/nginx -s reload fi endscript }ui
测试是否成功。操作系统
shell$ sudo logrotate -vf /etc/logrotate.conf #logrotate.conf中有include /etc/logrotate.d reading config file /etc/logrotate.conf including /etc/logrotate.d reading config file dracut reading config info for /var/log/dracut.log reading config file nginx reading config info for /data/logs/nginx_access.log /data/logs/nginx_error.log reading config file psacct reading config info for /var/account/pacct reading config file syslog reading config info for /var/log/cron /var/log/maillog /var/log/messages /var/log/secure /var/log/spoolerdebug
reading config file yum reading config info for /var/log/yum.log reading config info for /var/log/wtmp reading config info for /var/log/btmp
Handling 7 logs ...... rotating pattern: /data/logs/nginx_access.log /data/logs/nginx_error.log forced from command line (30 rotations) empty log files are not rotated, old logs are removed considering log /data/logs/nginx_access.log log needs rotating considering log /data/logs/nginx_error.log log needs rotating rotating log /data/logs/nginx_access.log, log->rotateCount is 30 dateext suffix '-20150827' glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' glob finding old rotated logs failed rotating log /data/logs/nginx_error.log, log->rotateCount is 30 dateext suffix '-20150827' glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' glob finding old rotated logs failed renaming /data/logs/nginx_access.log to /data/logs/nginx_access.log-20150827 creating new /data/logs/nginx_access.log mode = 0644 uid = 0 gid = 0 renaming /data/logs/nginx_error.log to /data/logs/nginx_error.log-20150827 creating new /data/logs/nginx_error.log mode = 0644 uid = 0 gid = 0 running postrotate script ......
从以上输出中咱们能够看出,两个日志都获得了rotate。