用途: 按照規則(日,周,日)對日志進行切割,壓縮,清除
安裝
centos系統默認安裝(系統使用該工具對系統日志進行切割)
yum -y install logrotate
配置文件說明
cat /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.
| 配置參數 | 說明 |
|---|---|
| weekly | 默認每一周執行一次rotate輪轉工作 |
| rotate 4 | 保留多少個日志文件(輪轉幾次).默認保留四個 |
| create | 自動創建新的日志文件,新的日志文件具有和原來的文件相同的權限;因為日志被改名,因此要創建一個新的來繼續存儲之前的日志 |
| dateext | 切割后的日志文件以當前日期為格式結尾,如xxx.log-20131216這樣,如果注釋掉,切割出來是按數字遞增,即前面說的 xxx.log-1這種格式 |
| include /etc/logrotate.d | # 將 /etc/logrotate.d/ 目錄中的所有文件都加載進來 |
其他重要參數說明
配置日志切割參數
| 參數 | 參數說明 |
|---|---|
| compress | 通過gzip 壓縮轉儲以后的日志 |
| nocompress | 不做gzip壓縮處理 |
| copytruncate | 用於還在打開中的日志文件,把當前日志備份並截斷;是先拷貝再清空的方式,拷貝和清空之間有一個時間差,可能會丟失部分日志數據。 |
| nocopytruncate | 備份日志文件不過不截斷 |
| create mode owner group | 輪轉時指定創建新文件的屬性,如create 0777 nobody nobody |
| nocreate | 不建立新的日志文件 |
| delaycompress | 和compress 一起使用時,轉儲的日志文件到下一次轉儲時才壓縮 |
| nodelaycompress | 覆蓋 delaycompress 選項,轉儲同時壓縮。 |
| missingok | 如果日志丟失,不報錯繼續滾動下一個日志 |
| errors address | 專儲時的錯誤信息發送到指定的Email 地址 |
| ifempty | 即使日志文件為空文件也做輪轉,這個是logrotate的缺省選項。 |
| notifempty | 當日志文件為空時,不進行輪轉 |
| mail address | 把轉儲的日志文件發送到指定的E-mail 地址 |
| nomail | 轉儲時不發送日志文件 |
| olddir directory | 轉儲后的日志文件放入指定的目錄,必須和當前日志文件在同一個文件系統 |
| noolddir | 轉儲后的日志文件和當前日志文件放在同一個目錄下 |
| sharedscripts | 運行postrotate腳本,作用是在所有日志都輪轉后統一執行一次腳本。如果沒有配置這個,那么每個日志輪轉后都會執行一次腳本 |
| prerotate | 在logrotate轉儲之前需要執行的指令,例如修改文件的屬性等動作;必須獨立成行 |
| postrotate | 在logrotate轉儲之后需要執行的指令,例如重新啟動 (kill -HUP) 某個服務!必須獨立成行 |
| daily | 指定轉儲周期為每天 |
| weekly | 指定轉儲周期為每周 |
| monthly | 指定轉儲周期為每月 |
| rotate count | 指定日志文件刪除之前轉儲的次數,0 指沒有備份,5 指保留5 個備份 |
| dateext | 使用當期日期作為命名格式 |
| dateformat .%s | 配合dateext使用,緊跟在下一行出現,定義文件切割后的文件名,必須配合dateext使用,只支持 %Y %m %d %s 這四個參數 |
| size(或minsize) log-size | 當日志文件到達指定的大小時才轉儲,log-size能指定bytes(缺省)及KB (sizek)或MB(sizem). |
- 示例
cat /etc/logrotate.d/nginx
/var/log/nginx/*log {
create 0644 nginx nginx
daily
dateext
rotate 7
missingok
notifempty
compress
sharedscripts
postrotate
/bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
endscript
}
logrotate命令使用說明
示例:
/usr/sbin/logrotate -f /etc/logrotate.d/nginx
| 參數 | 說明 |
|---|---|
| -d, --debug | debug模式,測試配置文件是否有錯誤。 |
| -f, --force | 強制轉儲文件。 |
| -m, --mail=command | 壓縮日志后,發送日志到指定郵箱。 |
| -s, --state=statefile | 使用指定的狀態文件。 |
| -v, --verbose | 顯示轉儲過程。 |
