如何获取触发查询的代码行?

时间:2012-06-06 09:18:35

标签: ruby-on-rails ruby activerecord logging

在rails 3.2中有一种方法(一个gem,一个插件或其他东西)来知道哪一行代码触发了数据库查询? 例如,在我的日志中,我有:

User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 5 LIMIT 1

我如何知道触发查询的代码行? THX ...

4 个答案:

答案 0 :(得分:26)

我找到了这个解决方案:

module QueryTrace
  def self.enable!
    ::ActiveRecord::LogSubscriber.send(:include, self)
  end

  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)
    trace_log = Rails.backtrace_cleaner.clean(caller).first
    if trace_log && event.payload[:name] != 'SCHEMA'
      logger.debug("   \\_ \e[33mCalled from:\e[0m " + trace_log)
    end
  end
end

在某些初始值设定项中添加QueryTrace.enable!

答案 1 :(得分:8)

使用active-record-query-trace gem:

Gemfile

gem 'active_record_query_trace'

然后bundle,然后在config/environments/development.rb

ActiveRecordQueryTrace.enabled = true

答案 2 :(得分:0)

将其添加到您的config/environments/test.rb或您想要插入线路的任何环境中。我正在5导轨上进行测试。

  ActiveRecord::Base.verbose_query_logs = true

您将获得文件和行。

答案 3 :(得分:-1)

你可以修补BufferedLogger来做你想要的。将此文件放在config/initializers路径中:

require 'active_support/buffered_logger'

class ActiveSupport::BufferedLogger

  def add(severity, message = nil, progname = nil, &block)
    add_debugging_details(severity)
    @log.add(severity, message, progname, &block)
  end

  private

  EXCLUDE_CALLERS = Gem.paths.path.clone << 'script/rails' << RbConfig::CONFIG['rubylibdir'] << __FILE__

  def add_debugging_details(severity)
    caller_in_app = caller.select do |line|
      EXCLUDE_CALLERS.detect { |gem_path| line.starts_with?(gem_path) }.nil?
    end

    return if caller_in_app.empty?

    @log.add(severity, "Your code in \e[1;33m#{caller_in_app.first}\e[0;0m triggered:")
  end

end if Rails.env.development?