Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

QueryTrace... ported to rails3

View query_trace.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
require 'term/ansicolor'
 
# yeilds a stacktrace for each SQL query
# put this file in config/initializers
class QueryTrace < ActiveSupport::LogSubscriber
include Term::ANSIColor
attr_accessor :trace_queries
 
def sql(event) #:nodoc:
return unless QueryTrace.enabled? && logger.debug? && Rails.env.development?
stack = Rails.backtrace_cleaner.clean(caller)
first_line = stack.shift
return unless first_line
 
msg = prefix + bold + cyan + "#{first_line}\n" + reset
msg += cyan + stack.join("\n") + reset
debug msg
end
 
# :call-seq:
# Klass.enabled?
#
# yields boolean if SQL queries should be logged or not
 
def self.enabled?
defined?(@trace_queries) && @trace_queries
end
 
# :call-seq:
# Klass.status
#
# yields text if QueryTrace has been enabled or not
 
def self.status
QueryTrace.enabled? ? 'enabled' : 'disabled'
end
 
# :call-seq:
# Klass.enable!
#
# turn on SQL query origin logging
 
def self.enable!
@trace_queries = true
end
 
# :call-seq:
# Klass.disable!
#
# turn off SQL query origin logging
 
def self.disable!
@trace_queries = false
end
 
# :call-seq:
# Klass.toggle!
#
# Toggles query tracing yielding a boolean indicating the new state of query
# origin tracing
 
def self.toggle!
enabled? ? disable! : enable!
enabled?
end
 
protected
 
def prefix #:nodoc:
bold(magenta('Called from: ')) + reset
end
end
 
QueryTrace.attach_to :active_record
 
trap('QUIT') do
# Sending 2 backspace characters removes the ^\ that is
# printed to the console.
rm_noise = "\b\b"
 
QueryTrace.toggle!
puts "#{rm_noise}=> QueryTrace #{QueryTrace.status}"
end
 
QueryTrace.enable! if ENV['QUERY_TRACE']
puts "=> QueryTrace #{QueryTrace.status}; CTRL-\\ to toggle"

Thanks for this. I had to add gem 'term-ansicolor' to my gemfile to get it working.

For rails 3 see this as an alternative https://github.com/flyerhzm/bullet

Holy shit, you guys shouldn't trap QUIT without actually quitting afterwards…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.