使用logrotate切割nginx日誌文件,其他日誌文件切割類似

首先安裝logrotate

以centos爲例

yum -y install logrotate

如果不需要切割其他的日誌則把

/etc/logrotate.conf中的

/var/log/wtmp {
    monthly
    create 0664 root utmp
       minsize 1M
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0600 root utmp
    rotate 1
}

去掉或者註釋掉

刪除掉/etc/logrotate.d下的文件,然後新建一個nginx

vi  /etc/logrotate.d/nginx

內容如下

/home/kong/logs/proxy/*.log {

daily

missingok

rotate 90

dateext

#compress

delaycompress

notifempty

create 777 root root

sharedscripts

postrotate

kong restart   #我使用的是kong網關,kong網關重啓使用命令kong restart 如果使用的是普通nginx則可使用( [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
                            //重啓nginx,重新加載日誌文件,防止不寫
            `cp -f /var/log/nginx/*.* /var/log/nginx/backup`
                            //自定義腳本,將舊日誌copy到backup文件夾(backup要存在))

endscript

}

其中各個配置解釋如下:

compress                        通過gzip壓縮轉儲以後的日誌
nocompress                      不壓縮
copytruncate                    用於還在打開中的日誌文件,把當前日誌備份並截斷
nocopytruncate                  備份日誌文件但是不截斷
create mode owner group         轉儲文件,使用指定的文件模式創建新的日誌文件
nocreate                        不建立新的日誌文件
delaycompress 和 compress        一起使用時,轉儲的日誌文件到下一次轉儲時才壓縮
nodelaycompress                 覆蓋 delaycompress 選項,轉儲同時壓縮。
errors address                   專儲時的錯誤信息發送到指定的Email 地址
ifempty                         即使是空文件也轉儲,這個是 logrotate 的缺省選項。
notifempty                      如果是空文件的話,不轉儲
mail address                    把轉儲的日誌文件發送到指定的E-mail 地址
nomail                          轉儲時不發送日誌文件
olddir directory                轉儲後的日誌文件放入指定的目錄,必須和當前日誌文件在同一個文件系統
noolddir                        轉儲後的日誌文件和當前日誌文件放在同一個目錄下
prerotate/endscript             在轉儲以前需要執行的命令可以放入這個對,這兩個關鍵字必須單獨成行
daily                           指定轉儲週期爲每天
weekly                          指定轉儲週期爲每週
monthly                         指定轉儲週期爲每月
rotate count                    指定日誌文件刪除之前轉儲的次數,0 指沒有備份,5 指保留5 個備份
tabootext [+] list 讓logrotate   不轉儲指定擴展名的文件,缺省的擴展名是:.rpm-orig, .rpmsave, v, 和 ~ 
size size                       當日志文件到達指定的大小時才轉儲,bytes(缺省)及KB(sizek)或MB(sizem)

 

查看logrotate默認執行時間

logrotate切割時間默認是在每天的3:22。這個時間點可以通過crontab配置文件查看到。如下:

cat /etc/anacrontab

SHELL=/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin

MAILTO=root

# the maximal random delay added to the base delay of the jobs

RANDOM_DELAY=45

# the jobs will be started during the following hours only

START_HOURS_RANGE=3-22

1 5 cron.daily nice run-parts /etc/cron.daily

7 25 cron.weekly nice run-parts /etc/cron.weekly

@monthly 45 cron.monthly nice run-parts /etc/cron.monthly

其中START_HOURS_RANGE參數就是配置logrotate切割的時間點。

執行logrotate -vf /etc/logrotate.d/nginx 測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章