Log every SQL query to database in Rails

后端 未结 6 1531
梦毁少年i
梦毁少年i 2020-12-03 17:40

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

6条回答
  •  悲&欢浪女
    2020-12-03 17:52

    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
    

提交回复
热议问题