Last active
September 24, 2019 10:48
-
-
Save loicginoux/a504033cfbe9065da1c23b45cbd79eaa to your computer and use it in GitHub Desktop.
how to know which sql query comes from which line of code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# file config/initializers/active_record_log_subscriber.rb | |
### | |
# log result: | |
# Alert Load (0.8ms) SELECT `alerts`.* FROM `alerts` INNER JOIN `sharings` ON `alerts`.`id` = `sharings`.`alert_id` WHERE `sharings`.`user_id` = 37 AND `alerts`.`id` = 54148 AND (status = 0) LIMIT 1 | |
# ↳ app/controllers/entries_controller.rb:20:in `set_objects' | |
# source: http://www.jkfill.com/2015/02/14/log-which-line-caused-a-query/ | |
### | |
module LogQuerySource | |
def debug(*args, &block) | |
return unless super | |
backtrace = Rails.backtrace_cleaner.clean caller | |
relevant_caller_line = backtrace.detect do |caller_line| | |
!caller_line.include?('/initializers/') | |
end | |
if relevant_caller_line | |
logger.debug(" ↳ #{ relevant_caller_line.sub("#{ Rails.root }/", '') }") | |
end | |
end | |
end | |
ActiveRecord::LogSubscriber.send :prepend, LogQuerySource |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment