0

作为这篇文章的后续:我正在尝试记录所有正在生成的查询。我已经尝试将它放在初始化程序中,并且直接在控制台中运行它并执行似乎永远不会被执行。

我尝试了以下方法:

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
    raise "THROW 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

然后运行

Person.last

而且我仍然没有错误。

4

1 回答 1

0

您无需对 ActiveRecord 进行猴子补丁即可获取日志记录(无论如何您在这里做错了)。我假设您希望在生产中使用它,因为在开发中所有查询都已记录。只需将其设置为config/environments/production.rb

config.log_level = :debug

或者,如果您只想将其限制为 SQL 查询,而不需要其他冗长,请尝试以下操作:

ActiveRecord::Base.logger.level = Logger::DEBUG

Or if your goal is to write the SQL queries to a dedicated logfile, check out this question: Rails3 SQL logging output in a separate file

于 2012-11-07T18:06:20.353 回答