views:

951

answers:

4

I want to save to a log file some SQL query rails performs, (namely the CREATE, UPDATE and DELETE ones) therefore I need to intercept all queries and then filter them maybe with some regexp and log them as needed.

Where would I put such a thing in the rails code?

A: 

SQL Server? If so...

Actually, I'd do this at the SQL end. You could set up a trace, and collect every query that comes through a connection with a particular Application Name. If you save it to a table, you can easily query that table later.

Rob Farley
+4  A: 

SQL logging in rails - In brief - you need to override ActiveRecord execute method. There you can add any logic for logging.

c0r0ner
And remember to not intercept the logging queries themselves, or you'll get an infinite loop...
DanSingerman
+2  A: 

Here a simplified version of what c0r0ner linked to, to better show it:

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
luca
A: 

If you are using mysql I would look into mysqlbinlog . It is going to track everything that potentially updates data. you can grep out whatever you need from that log easily.

http://dev.mysql.com/doc/refman/5.0/en/mysqlbinlog.html

http://dev.mysql.com/doc/refman/5.0/en/binary-log.html

cgr