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。