John Hawthorn

Rails logging to console

One of the best tools in a rails developers arsenal is the rails console, being extremely useful for brainstorming, debugging, and testing. Having it log active record queries directly to the console can improve readability and convenience over looking through the development logs to see what SQL queries have been run.


ruby > User.first => #<User id: 1, ...


ruby > User.first User Load (0.4ms) SELECT "users".* FROM "users" LIMIT 1 => #<User id: 1, ...

This works with both rails 2 and rails 3 by adding the following lines to ~/.irbrc

if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER') # for rails 2 require 'logger' RAILS_DEFAULT_LOGGER = elsif defined?(Rails) # for rails 3 require 'logger' ActiveRecord::Base.logger = end

The same can be accomplished though editing environment.rb but I’d prefer to use this method as it will apply to any rails project without modification.