Easy log rotation with Rails 5
Few months back, one of my application server crashed several times. Upon looking into the server logs, I found out application was not able to write logs. So I checked for disk space usage.
du -a /home | sort -nr | head -n 5
The above command provide you with top 5 space occupying directories in the /home location. Turned out the log files consumed all the server space.
As the application server is processing requests, it creates log files. Initially you might not see any problem with that. However if the log files keep growing they can outrun the disk space and your application server can crash. Luckily Rails has a quick and easy solution to this, that you can control from the code itself.
This is what you need in your config/environments/production.rb
# Keeps the Last 5 log files which are rotated at every 10MB
config.logger = Logger.new(config.paths[“log”].first, 5, 10.megabytes)
This way your Rails application logs will never consume more than 50MB space on the server.
There is another tool namely logrotate for the same purpose. But that is another server dependency, you need to manage. If you want to try it out, use the following command in terminal to see available options for logrotate tool.
Logrotate tool can be helpful if you need to do some advance stuff, such as emailing logs before deletion or executing a script after deletion.
Happy log rotating :)