2012-11-07 36 views
0

作为此后续从post:我试图记录正在生成的所有查询。我曾尝试将它放在初始化程序中,并且只是直接在控制台中运行它,并且执行似乎不会执行。Rails 2.3单独记录所有数据库查询

我曾尝试以下:

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 

我仍然没有错误。

回答

0

你不需要猴子补丁ActiveRecord来获取日志记录(无论如何你在这里做错了)。我假设你想在生产中使用它,因为在开发过程中所有查询都已经记录。只需设置这config/environments/production.rb

config.log_level = :debug 

或者,如果你想限制这SQL只查询,没有其他冗长,试试这个:

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

或者,如果你的目标是编写SQL查询到一个专门的日志文件,看看这个问题:Rails3 SQL logging output in a separate file

+0

第三个职位帮了我。谢谢 –