Log every SQL query to database in Rails

后端 未结 6 1532
梦毁少年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

    Slightly updated version of @luca's answer for at least Rails 4 (and probably Rails 5)

    Place this in config/initializers/sql_logger.rb:

    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.log"), 'a') do |file|
            file.puts Time.now.to_s + ": " + sql
          end
        rescue Exception => e
          "Error logging SQL: #{e}"
        end
        # execute original statement
        original_exec(sql, *name)
      end
    end
    

提交回复
热议问题