Skip to content

Instantly share code, notes, and snippets.

@brentd
Created April 14, 2010 19:50
Show Gist options
  • Save brentd/366249 to your computer and use it in GitHub Desktop.
Save brentd/366249 to your computer and use it in GitHub Desktop.
Temporarily redirect ActiveRecord query logging
# Semi-evil way to force ActiveRecord to temporarily redirect where it's
# logging SQL queries. Quick way to find out why the crap that query
# isn't working - helpful especially when debugging a failing test.
#
# Can't use `ActiveRecord::Base.logger = foo` because that'll only work for
# new DB connections. Can't just reset connections because doing so in the
# middle of a test would abort transactions.
#
# So we resort to evil...
#
# Example:
#
# log_to(STDOUT) { Person.all } #=> "SELECT * FROM people;"
#
def log_to(stream)
old_logger = ActiveRecord::Base.connection.instance_variable_get(:@logger)
ActiveRecord::Base.connection.instance_variable_set(:@logger, Logger.new(stream))
yield
ActiveRecord::Base.connection.instance_variable_set(:@logger, old_logger)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment