Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log every SQL query to database in Rails

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?

like image 489
luca Avatar asked Oct 27 '09 08:10

luca


1 Answers

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.open(Rails.root.join("/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
like image 196
luca Avatar answered Sep 30 '22 16:09

luca