跟踪 Rails 3 SQL 查询 [英] Tracing Rails 3 SQL queries

查看:43
本文介绍了跟踪 Rails 3 SQL 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何适用于 Rails 3 的 gem 可以显示我的代码的哪一部分生成了哪个 SQL 查询?

Is there any gem which works on Rails 3 that can show which part of my code generated which SQL query?

在 Rails 2.3 上有一个名为 query_trace 的插件,但它似乎不适用于 Rails 3,它会产生以下错误:

On Rails 2.3 there was plugin called query_trace, but it doesn't seem to work on Rails 3, it generates following error:

alias_method': undefined method `log_info' for class `ActiveRecord::ConnectionAdapters::AbstractAdapter' (NameError)

推荐答案

QueryTrace 无法按原样工作,因为 Rails 3 esp 中的 ActiveRecord 区域进行了许多更改.

QueryTrace doesn't work as-is because many changes were made in Rails 3 esp in the area of ActiveRecord.

所以,我偷偷摸摸地把它弄成这样:

So, hacking around, I made it work like this:

您只需要上述位置中的以下 2 个文件.然后重新启动 Web 服务器.在 SQL 之后,您应该在控制台(白色洋红色)和日志文件中看到 Called from:

You just need the 2 files below in the locations mentioned. Then restart the web server. After the SQL, you should see Called from: in a console (magenta on white) and log file

/vendor/plugins/query_trace/lib/query_trace.rb

module QueryTrace
  def self.append_features(klass)
    super
    klass.class_eval do
      unless method_defined?(:log_info_without_trace)
        alias_method :log_info_without_trace, :sql
        alias_method :sql, :log_info_with_trace
      end
    end
  end

  def log_info_with_trace(event)
    log_info_without_trace(event)
    logger.debug("\e[1m\e[35m\e[1m\e[47mCalled from:\e[0m " + clean_trace(caller[2..-2]).join("\n "))
  end

  def clean_trace(trace)
    Rails.respond_to?(:backtrace_cleaner) ?
      Rails.backtrace_cleaner.clean(trace) :
      trace
  end
end

/vendor/plugins/query_trace/init.rb

require 'query_trace'

class ::ActiveRecord::LogSubscriber
  include QueryTrace
end

这篇关于跟踪 Rails 3 SQL 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆