Nginx 日志轮询及压缩保存天数
一、日志需求
1. Nginx的访问日志及访问错误日志,默认是保存在一个指定的文件内,如果访问量很大,文件会变的很大,影响的日志写入的速度及备份,因此需要对nginx的日志进行按日分割并进行压缩,压缩日志保存30天(根据需要调节)
二、解决方案
使用cron 和 logrotate 来管理日志文件
1. 编写nginx的logrotate配置文件,并将文件放到/etc/logrotate.d目录下,权限0644
# ll /etc/logrotate.d/ -rw-r--r-- 1 root root 194 Apr 12 21:50 httpd -rw-r--r-- 1 root root 868 Aug 17 18:12 mysql -rw-r--r-- 1 root root 255 Sep 20 08:29 nginx -rw-r--r-- 1 root root 203 Nov 6 2016 php-fpm -rw-r--r--. 1 root root 136 Jun 10 2014 ppp -rw-r--r--. 1 root root 224 Sep 8 2015 syslog -rw-r--r--. 1 root root 100 Jun 16 2015 wpa_supplicant -rw-r--r--. 1 root root 100 Dec 3 2015 yum
nginx 文件内容
vim /etc/logrotate.d/nginx
# nginx logrotate # # mimvp.com # 2017.9.1 /var/log/nginx/*log { create 0644 nginx nginx daily rotate 10 missingok notifempty compress sharedscripts postrotate /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true endscript }
httpd 文件内容
vim /etc/logrotate.d/httpd
/data/httplogs/*.log { daily rotate 30 missingok notifempty compress sharedscripts olddir /data/httplogs/old_log postrotate /bin/kill -HUP `cat /var/run/nginx.pid 2> /dev/null` 2> /dev/null || true endscript }
配置参数说明:
/data/httplogs/*.log nginx访问日志文件存放的目录,默认是所有.log文件
日志每天截断并压缩,保留30天的数据(空日志文件不处理)
压缩的日志文件存储到指定的日志保存目录 /data/httplogs/old_log
在日志截断后,重启nginx,以便生成新的访问日志
2. 确认 logrotate 运行正常
1)检查 logrotate主配置文件/etc/logrotate.conf
vim /etc/logrotate.conf
# see "man logrotate" for details # rotate log files weekly weekly # keep 4 weeks worth of backlogs rotate 4 # create new (empty) log files after rotating old ones create # use date as a suffix of the rotated file dateext # uncomment this if you want your log files compressed #compress # RPM packages drop log rotation information into this directory include /etc/logrotate.d # no packages own wtmp and btmp -- we'll rotate them here /var/log/wtmp { monthly create 0664 root utmp minsize 1M rotate 1 } /var/log/btmp { missingok monthly create 0600 root utmp rotate 1 } # system-specific logs may be also be configured here.
2) 确认/etc/cron.daily/下面有logrotate脚本
# ll /etc/cron.daily/ -rwxr-xr-x. 1 root root 332 Dec 3 2015 0yum-daily.cron -rwx------. 1 root root 180 Jul 31 2013 logrotate -rwxr-xr-x. 1 root root 618 Mar 18 2014 man-db.cron
3) 查看脚本内容 /etc/cron.daily/logrotate
vim /etc/cron.daily/logrotate
#!/bin/sh /usr/sbin/logrotate /etc/logrotate.conf EXITVALUE=$? if [ $EXITVALUE != 0 ]; then /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]" fi exit 0
参考推荐:
Nginx 使用 cron 和 logrotate 管理日志文件
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2018-01-06 22:05:06
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
转载注明: Nginx 日志轮询及压缩保存天数 (米扑博客)
文章不错支持一下吧