Skip to content

Instantly share code, notes, and snippets.

@mattscilipoti
Created February 20, 2011 05:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattscilipoti/835724 to your computer and use it in GitHub Desktop.
Save mattscilipoti/835724 to your computer and use it in GitHub Desktop.
Rails3: Log slow queries.
# see: http://weblog.therealadam.com/2011/02/12/simple-ruby-pleasures/comment-page-1/#comment-315
class QueryTracer < ActiveSupport::LogSubscriber
ACCEPT = %r{^(app|config|lib)}.freeze
FRAMES = 5
THRESHOLD = 300 # In ms
def sql(event)
return unless event.duration > THRESHOLD
callers = Rails.
backtrace_cleaner.
clean(caller).
select { |f| f =~ ACCEPT }.
take(FRAMES).
map { |f| f.split(":").take(2).join(":") }.
join(" | ")
# Shamelessly stolen from ActiveRecord::LogSubscriber
warning = color("SLOW QUERY", RED, true)
name = '%s (%.1fms)' % [event.payload[:name], event.duration]
sql = event.payload[:sql].squeeze(' ')
warn " #{warning}"
warn " #{name} #{sql}"
warn " Trace: #{callers}"
end
end
QueryTracer.attach_to :active_record
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment