LoginSignup
9
7

More than 5 years have passed since last update.

rails5 + unicorn + nginx : ログローテーション

Last updated at Posted at 2016-08-03

ログの容量が増えると管理しにくいことと追跡が難しくなるため、ログローテーションをしたい。

rails関連のログローテーションをlogrotateで管理する。

logrotateにログローテーションを作成する

まずlogrotate.d配下にあるものを確認してみる。

$cd /etc/logrotate.d

$ls -l

合計 36
-rw-r--r-- 1 root root 103  9月 14  2015 dracut
-rw-r--r-- 1 root root 185  3月  7 23:48 httpd
-rw-r--r-- 1 root root 118  6月 23 09:42 mackerel-agent
-rw-r--r-- 1 root root 907 11月 11  2015 mysqld
-rw-r--r-- 1 root root 204  2月 19 22:52 nginx
-rw-r--r-- 1 root root 329  9月 10  2014 psacct
-rw-r--r-- 1 root root 210 11月 11  2014 syslog
-rw-r--r-- 1 root root 100 10月 15  2015 yum

ログローテーション設定ファイルを作成します。

touch unicorn

作成したファイルに設定を記載します。

$sudo vim unicorn

/var/www/rails/app/current/log/*.log {
  daily
  missingok
  rotate 7
  dateext

  compress
  delaycompress
  copytruncate

  create 0666 ec2-user ec2-user

  lastaction
    pid=/var/www/app/current/tmp/pids/unicorn.pid
    test -s $pid && kill -USR1 "$(cat $pid)"
  endscript
}
  • daily:ログローテーションを毎日行う
  • missingok:指定のログファイルがなくてもエラーを出さずに処理を続行する
  • rotate:ログローテートの世代管理は7
  • dateext:ログローテートを日付形式にする
  • lastaction~endscript
    • unicornには、USR1シグナル(プロセスの動作を中断させたり、再開、変更といった合図を送るための指定)を送ると、ログファイルを開き直してくれる機能があります。
    • test -s \$pid「ファイルが存在すれば」kill -USR1 "\$(cat \$pid)"「pidをUSR1でkillする

テスト

設定が終了したらテストで実行してみます。

$cd /etc/logrotate.d

$logrotate -df /etc/logrotate.d/unicorn
  • d : デバッグモード
  • f : 強制実行

実行(手動で適用)

$logrotate -f /etc/logrotate.d/unicorn

$ls -l /var/www/rails/app/current/log

total 652
-rw-rw-r-- 1 vagrant vagrant 553843 Sep 20 12:19 development.log-20160213
-rw-rw-r-- 1 vagrant vagrant  99141 Sep 20 12:19 unicorn.stderr.log-20160213
-rw-rw-r-- 1 vagrant vagrant      0 Dec 21  2014 unicorn.stdout.log-20160213

logrotateはcronから起動されるので、以上で設定完了です。再起動は不要です。

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7