Log every SQL query to database in Rails 3

2019-05-20 22:47发布

This question is a follow up to this question, where should I place this code?

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
        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

I have tried placing it inside of the model, but what happens is when I execute some sql query more then once it returns "stack level is to deep" error.

1条回答
三岁会撩人
2楼-- · 2019-05-20 23:41

Put it in config/initializers. Most likely it's because of reloading classes each time in dev env. This code need to be executed only once though.

查看更多
登录 后发表回答