使用logrotate做日志切分(以nginx为例)

问题原因

       对于一些长期运行的服务,日志会越积越多,如果没有很好地切分丢弃废弃日志的处理逻辑,日志文件会一直膨胀下去,无论是从日志过滤还是从服务器存储角度来讲都是很不友好的,所以需要对日志进行切分处理

前提条件

服务器已安装logrotate,如果没有,可执行以下命令进行安装

yum -y install logrotate

logrotate配置

进入/etc/logrotate.d/目录,logrotate会扫描该目录下的配置文件进行执行,在该目录下创建nginx文件
注:logrotate入口文件是/etc/logrotate.conf

/date/logs/nginx/access.log {
    daily # 按天轮换日志
    rotate 7 # 在轮换方案中包含日志的 n 个版本
    missingok # 如果日志文件丢失,不要显示错误
    dateext # 就是切割后的日志文件以当前日期为格式结尾
    notifempty # 当日志文件为空时,不进行轮转
    compress # 通过gzip 压缩转储以后的日志
    delaycompress # 和compress 一起使用时,转储的日志文件到下一次转储时才压缩
    sharedscripts # 运行postrotate脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本
    postrotate # 执行脚本
        /bin/kill -USR1 $(cat /var/run/nginx.pid 2>/dev/null) 2>/dev/null || :
    endscript
}

验证配置是否生效正确可通过以下命令手动执行一次

logrotate -df /etc/logrotate.conf

通过crontab维护lograte

配置/etc/crontab文件,插入以下定时任务

0 * * * *   root    cd / && run-parts --report /etc/cron.hourly
0 0 * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
0 0 * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
0 0 1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

重启crontabcrond restart

你可能感兴趣的:(使用logrotate做日志切分(以nginx为例))