Railsのログをlogrotateする

Railsproduction.log などのログは、際限なく容量が増えるため、古いものから削除するなどの必要があります。これをログのローテーションと言います。

Linuxではlogrotateを使うことが一般的ですが、ローテーション後に、アプリケーションサーバーが新たにログを書き出せなくなる問題があります。これは、logrotateが新しいログファイルにした際に、アプリケーションサーバーが新しいログファイルの検知に失敗するために発生します。

この問題は、次のようにlogrotateのオプションに copytruncate を追加することで解決できます。このオプションは、新たにログファイルを作成するのではなく、ログをコピーして古いログをファイルの中身を空にするものです。

$ cat /etc/logrotate.d/my_rails_app
/var/www/my_rails_app/log/*.log {
  weekly
  missingok
  rotate 280
  compress
  delaycompress
  create 0664 ec2-user ec2-user 
  copytruncate
}

参考

copytruncate – Copy the log file and then empties it. This makes sure that the log file Rails is writing to always exists so you won’t get problems because the file does not actually change. If you don’t use this, you would need to restart your Rails application each time.

gorails.com

補足

ログのローテーション後に、pumaというアプリケーションサーバーに次のようなシグナルを送り、ログのリオープンを指示したが、うまく行きませんでした。

$ kill -HUP $puma_pid 

tech.basicinc.jp