Any person who has worked with a rails application for a good amount of time would have faced the issue of log files growing and consuming the entire space in the hard disk. Although this sounds funny, it does happen if you do not place a log management for your rails app (in production). You can manage your logs using log rotation. Do note that log rotation is not required if you host your app in heroku, as heroku won’t let you store files for more than 15 minutes in their server. You also do not need it if you are using some third party services like loggly or papertrail to manage your logs .
In the unix world, you can use log rotate service, which would be installed by default in all linux servers. But we at Red Panthers feel that everything that touches or involves our rails application should be placed along with our rails application as much as possible. If you feel the same way, it can be achieved by placing the code below in the production.rb file.
config.logger = Logger.new( Rails.root.join("log", Rails.env + ".log" ), 5 , 100 * 1024 * 1024 )
The Logger.new accepts three parameters:
- The file name, which would be production.log
- The number of files you want to keep
- The size of each file in bytes. (100 * 1024*1024 means 100 MB)
So, when the time comes to add the 6th 100 MB log file, it will delete the oldest.
For those who still want to use the unix log rotate, they should create a new config file at
/etc/logrotate.d/myrailsapp-config as shown below
$ cat /etc/logrotate.d/myrailsapp-config
In case you were wondering, here are what these options mean:
- compress – Compress logs using gzip
- copytruncate – Copy the log out of the way, and then truncate the existing logs
- daily – Rotate daily
- dateext – Add the date the logs were rotated as the extension instead of a number
- delaycompress – Skip compressing the log until the following day
- missingok – Do not raise an error when there is a missing log file
- rotate 90 – Keep up to 90 days worth of logs