Your Rails application log files can grow forever in your servers if you don't do anything to avoid it, making it more difficult to search them for info when things go wrong or even making your server run out of disk space.
But it's easy to keep your log files in check with logrotate
. First make sure it's installed in your system, it's part of the Ubuntu default installation, but if it isn't there you can install it with:
sudo apt-get install logrotate
Then you can add your configuration either in /etc/logrotate.conf
or in a separate file inside /etc/logrotate.d
.
For this example create the new file /etc/logrotate.d/my_rails_app
and paste the following there:
/path/to/rails_app/log/*.log {
su rails_app_user rails_app_user
daily
missingok
dateext
rotate 7
compress
delaycompress
notifempty
copytruncate
}
This will rotate *.log files inside /path/to/rails_app/log/
daily, and keep logs for 7 days.
- su: tells logrotate which user/group should be used for rotation
- daily/weekly/monthly: tells logrotate how often to rotate files
- missingok: ignore the file if it doesn't exist
- dateext: use a date suffix for the file instead of just a sequence number
- rotate N: how many periods to keep (of the ones defined in the second line: days, weeks or months)
- compress: compress rotated log files
- delaycompress: compress the rotated log files next time the log file is rotated, to make sure it doesn't interfere with the server being run
- notifempty: skip rotation if the log file is empty
- copytruncate: makes a backup copy of the current log and then clears the log file for continued writing, this way you don't need to restart the server each time the log is rotated
Another example that rotates logs weekly and keeps the logs for a year (52 weeks):
/path/to/rails_app/tmp/log/*.log {
su rails_app_user rails_app_user
weekly
missingok
dateext
rotate 52
compress
delaycompress
notifempty
copytruncate
}
Then, to test what your new config file would do you can run it in debug mode (it's also a dry-run mode, it won't do anything, just show what it would do):
/usr/sbin/logrotate -d /etc/logrotate.d/my_rails_app
If you want to run the file right now and not wait until it rotates the files in the normal daily run, you can do so with:
/usr/sbin/logrotate -fv /etc/logrotate.d/my_rails_app
-
f option is to force the run, it's the same as
--force
- v option is to have a verbose output of what logrotate is doing