Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choonkeat/0c39794b7de60468fbec to your computer and use it in GitHub Desktop.
Save choonkeat/0c39794b7de60468fbec to your computer and use it in GitHub Desktop.
Drop this file into config/initializers/ and enjoy SQL logging with stacktrace
# 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