As a follow up from this post: i am trying to log all queries that are being generated. I have tried placing this in an initializer, and also just straight up running it in console and execute never seems to get executed.
I have tried the following:
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
raise "THROW AN ERROR"
begin
file = File.open(RAILS_ROOT + "/log/sql.txt",'a'){|f| f.puts Time.now.to_s+": "+sql}
rescue Exception => e
;
end
# execute original statement
original_exec(sql, *name)
end
end
And then run
Person.last
And I still get no error.
You don’t need to monkey-patch ActiveRecord to get logging (which you’re doing incorrectly here anyway). I assume you want this in production, since in development all queries are already logged. Simply set this in
config/environments/production.rb:Or if you want to restrict this to SQL queries only, without the other verbosity, try this:
Or if your goal is to write the SQL queries to a dedicated logfile, check out this question: Rails3 SQL logging output in a separate file