Setting up SQL logs in Rails 2 and 3 console

When developing Rails applications, it is often desirable to see what ActiveRecord is doing behind the scenes when using the console. By default, log messages in script/console (Rails 2) or rails c (Rails 3) are only sent to log/development.log, which I find quite annoying to keep an eye on. Much better would be if it the messages were sent directly to the console itself.

It turns out that it is very simple to achieve that. Add the following code to your ~/.irbrc file:

# File ~/.irbrc
require 'logger'

# For Rails 2
RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)

# For Rails 3
ActiveRecord::Base.logger = Logger.new(STDOUT)

Simple as that. Restart the console and load any AR model, and the SQL statement should appear right before the data. For the same of simplicity, I set woth RAILS_DEFAULT_LOGGER and ActiveRecord::Base.logger, even because I had sittuations where only having one of the configurations didn’t work so well (for an unknown reason to me)