linux底下的logrotate


因為之前把一堆東西都加到去nginx的access log裡去(headers/device_id/etc.) 結果超巨量的log把硬碟整個塞爆了… 所以就研究了下有沒有簡單的log rotation方案可以用

Linux下的logrotate

linux上本身已有的logrotate功能 簡單設定就可以自動每天進行log rotation

設定

新增一個設定檔到 /etc/logrotate.d/nginx

/var/log/nginx/*.log {
  daily # 每天跑一次
  compress # 壓縮成gz
  delaycompress 
  rotate 3 # 每3輪就會rotate一次
  missingok # 不存在也是OK的!
  nocreate
  sharedscripts
  postrotate # rotate完之後的動作
    [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
  endscript
}

留意kill -USR1 nginx不是要關掉nginx,而是透過singal去通知nginx 重開log file 直接跑以下命令運行測試

logrotate -f -v /etc/logrotate.d/nginx

成功後就會看到一個access.log.1或者access.log.2.gz

參考