Using a Custom Logger with Rails

One of the great things about Rails is that of course it automatically does logging… and has different levels of logging for each environment.

Despite this, I had a couple of gripes: 1. The logger doesn’t have a formatter - i.e. in particular, it doesn’t include timestamps. 2. It doesn’t automatically rotate - and the development log can get MASSIVE (I’ve often had them 5GB+)

Additionally, I thought it’d be great if I could separate logs from ActiveRecord and ActionController.

Thankfully, Rails lets us choose the logger that we want to use. We’ll create our own and ask Rails to use it.

Step 1. Set up our logger

We’re using the default ruby Logger (see “http://ruby-doc.org/core/classes/Logger.html”:http://ruby-doc.org/core/classes/Logger.html).

In environment.rb:

active_record_logger = Logger.new(File.join(RAILS_ROOT, "log", "\#{RAILS_ENV}_active_record_log.log"), 'weekly')
action_controller_logger = Logger.new(File.join(RAILS_ROOT, "log", "\#{RAILS_ENV}_action_controller_log.log"), 'weekly')
active_record_logger.formatter = action_controller_logger.formatter = Logger::Formatter.new

Some notes and options here: * We’re putting the log file in the default location (RAILS_ROOT/log/) * This will still produce separate logs for each environment (dev, test, prod, etc) * This will do weekly rotation - but you could easily switch to ‘daily’ or 'monthly’ * We can also configure it to a maximum number of old logs + maximum size - see “the docs”:http://ruby-doc.org/core/classes/Logger.html#M001002 for more info.

Step 2. Ask Rails to use it

In the initializer block in environment.rb…

Rails::Initializer.run do |config|
  config.active_record.logger = active_record_logger
  config.action_controller.logger = action_controller_logger

  #...
end

That should be it. Enjoy.