Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the line of code that triggers a query?

is there a way (a gem, a plugin or something else) in rails 3.2 to know which line of code triggers a database query? For example in my log I have:

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

How can I know the line of code that triggers the query? Thx...

like image 428
Pioz Avatar asked Jun 06 '12 09:06

Pioz


3 Answers

I've found this solution:

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

In some initializer add QueryTrace.enable!

like image 148
Pioz Avatar answered Oct 02 '22 07:10

Pioz


Using the active-record-query-trace gem:

In Gemfile:

gem 'active_record_query_trace'

Then bundle, then in config/environments/development.rb:

ActiveRecordQueryTrace.enabled = true
like image 32
Dorian Avatar answered Oct 02 '22 07:10

Dorian


Rails 5.2+

Add this to your config/environments/test.rb or whatever environment you want to have the lines in. I am testing on rails 5.

  ActiveRecord::Base.verbose_query_logs = true

You'll get the file and the line.

like image 44
shampoo Avatar answered Oct 02 '22 08:10

shampoo