Log every SQL query to database in Rails 3

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.

Answers


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.


Need Your Help

How to merge “develop” branch from different people in git flow branching model?

git version-control merge git-branch git-flow

Is "develop" branch in git flow branching model shared by different people? So we have to manually push "develop" and pull it to merge?

Javascript syntax highlighting in vim

javascript vim editing vim-syntax-highlighting

Has anyone else found VIM's syntax highlighting of Javascript sub-optimal? I'm finding that sometimes I need to scroll around in order to get the syntax highlighting adjusted, as sometimes it

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.