Skip to content

Instantly share code, notes, and snippets.

@denmarkin
Created May 15, 2011 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denmarkin/973333 to your computer and use it in GitHub Desktop.
Save denmarkin/973333 to your computer and use it in GitHub Desktop.
Log all SQL statements in RoR 3 app. config/initializers/sql_logger.rb
# config/initializers/sql_logger.rb
connection = ActiveRecord::Base.connection
class << connection
alias :original_exec :execute
def execute(sql, *name)
# try to log sql command but ignore any errors that occur in this block
# we log before executing, in case the execution raises an error
begin
rails_env = ENV['RAILS_ENV'] || 'development'
file = File.open(Rails.root.to_s + "/log/sql_#{rails_env}.log",'a'){|f| f.puts Time.now.to_s+": "+sql} if (%w(staging development).include? rails_env)
rescue Exception => e
;
end
# execute original statement
original_exec(sql, *name)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment