nginx日志切割

使用系统自带的logrorate来切个nginx日志,位于/usr/sbin/logrotate

[root@PayServer haproxy]# cat /etc/logrotate.d/nginx 
/home/nginx/logs/*.log {  #指定切割日志文件路径
        daily
        missingok
        dateext
        rotate 365
        nocompress
        notifempty
        olddir /home/nginx/logs/days/  #指定切割后日志存放的位置
        create 755 root adm
        sharedscripts
        postrotate
                [ -f /home/nginx/logs/nginx.pid ] && kill -USR1 `cat /home/nginx/logs/nginx.pid`
        endscript
}

  • 需要注意的是你们的nginx.pid位置,不一定是在/home/nginx/logs/nginx.pid
 

 

配置说明
daily 指定转储周期为每天
weekly 指定转储周期为每周
monthly 指定转储周期为每月
rotate 转储次数,超过将会删除最老的那一个
missingok 忽略错误,如“日志文件无法找到”的错误提示
dateext 切换后的日志文件会附加上一个短横线和YYYYMMDD格式的日期
compress 通过gzip 压缩转储旧的日志
delaycompress 当前转储的日志文件到下一次转储时才压缩
notifempty 如果日志文件为空,不执行切割
sharedscripts 只为整个日志组运行一次的脚本
prerotate/endscript 在转储以前需要执行的命令可以放入这个对,这两个关键字必须单独成行
postrotate/endscript 在转储以后需要执行的命令可以放入这个对,这两个关键字必须单独成行

执行该命令测试

logrotate -vf /etc/logrotate.d/nginx

reading config file /etc/logrotate.d/nginx
reading config info for /home/nginx/logs/*.log 
olddir is now /home/nginx/logs/days/

Handling 1 logs

rotating pattern: /home/nginx/logs/*.log  forced from command line (365 rotations)
olddir is /home/nginx/logs/days/, empty log files are not rotated, old logs are removed
considering log /home/nginx/logs/access.log
  log does not need rotating
considering log /home/nginx/logs/error.log
  log needs rotating
rotating log /home/nginx/logs/error.log, log->rotateCount is 365
dateext suffix '-20180806'
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 /home/nginx/logs/error.log to /home/nginx/logs/days//error.log-20180806
creating new /home/nginx/logs/error.log mode = 0755 uid = 0 gid = 4
running postrotate script

查看生产的日志文件

每日0点执行脚本

  • 在终端运行 crontab -e
  • 插入以下语句
0 0 * * * /usr/sbin/logrotate -vf /etc/logrotate.d/nginx

参考链接:http://www.cnblogs.com/snowater/p/8340238.html
原文地址:https://www.cnblogs.com/hellojackyleon/p/9431050.html