Inline logging in Rails console

While trying out some code in console that deals with storage I find it really useful sometimes to have log output inline (and not in another window that tails the environment log) so I can see right there what’s going on - generated SQL that hits database as well as interaction with the cache store.

Here’s how you can set it up when needed:

# ActiveRecord - Rails 2
ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)

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

# Cache Store - Rails 2 & 3
ActiveSupport::Cache::Store.logger = Logger.new(STDOUT)

You can set this to run every time you’re in console by adding this in environment.rb

if "irb" == $0
  ActiveRecord::Base.logger = Logger.new(STDOUT)
  ActiveSupport::Cache::Store.logger = Logger.new(STDOUT)
end

This is how it looks like in my console while I’m developing my upcoming Rails plugin for caching:

>> User.last.cached(:profile)
  User Load (0.000581) (1 Row)   SELECT * FROM `users` ORDER BY users.id DESC LIMIT 1
Cache miss: User[65]#profile
  Profile Load (0.000454) (1 Row)   SELECT * FROM `profiles` WHERE (`profiles`.user_id = 65) LIMIT 1
Cache write (will save 1.64ms): User[65]#profile
=> #<Profile id: 65, first_name: nil, last_name: nil, ...>

Sweet, though I’d prefer if Cache Store would log raw commands to cache store (Redis, MemCache,…) just like ActiveRecord logs SQL.