Как получить строку кода, которая вызывает запрос? - программирование
Подтвердить что ты не робот

Как получить строку кода, которая вызывает запрос?

Есть ли способ (жемчужина, плагин или что-то еще) в rails 3.2 знать, какая строка кода запускает запрос базы данных? Например, в моем журнале я:

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

Как узнать строку кода, которая запускает запрос? спасибо...

4b9b3361

Ответ 1

Я нашел это решение:

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!

Ответ 2

Используя active-record-query-trace gem:

В Gemfile:

gem 'active_record_query_trace'

Тогда bundle, затем в config/environments/development.rb:

ActiveRecordQueryTrace.enabled = true

Ответ 3

Вы можете обезглавить патч 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?