Last active
August 29, 2015 14:01
-
-
Save choonkeat/0c39794b7de60468fbec to your computer and use it in GitHub Desktop.
Drop this file into config/initializers/ and enjoy SQL logging with stacktrace
This file contains 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
# set env FULL_STACKTRACE=1 for full stacktrace | |
# set env DEBUG_LOG=1 to turn this on (default off) | |
if defined?(ActiveRecord::LogSubscriber) | |
module ActiveRecord | |
class LogSubscriber | |
def sql(event) | |
self.class.runtime += event.duration | |
return unless logger.debug? | |
payload = event.payload | |
return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) | |
name = "#{payload[:name]} (#{event.duration.round(1)}ms)" | |
sql = payload[:sql] | |
binds = nil | |
unless (payload[:binds] || []).empty? | |
binds = " " + payload[:binds].map { |col,v| | |
render_bind(col, v) | |
}.inspect | |
end | |
if odd? | |
name = color(name, CYAN, true) | |
sql = color(sql, nil, true) | |
else | |
name = color(name, MAGENTA, true) | |
end | |
app_path = Rails.root.join("app").to_s | |
debug "#{Time.now.rfc822} #{name} #{sql}#{binds}; -- #{caller.join("\n")}" if ENV['FULL_STACKTRACE'] | |
debug "#{Time.now.rfc822} #{name} #{sql}#{binds}; -- #{caller.inject([]) {|sum,line| sum + (line.index(app_path) ? [line[app_path.length+1..-1]] : []) }[0..ENV['ACTIVERECORD_STACKTRACE_DEPTH'].to_i]}" unless ENV['FULL_STACKTRACE'] | |
end | |
end | |
end | |
end if ENV['DEBUG_LOG'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment