Skip to content

Instantly share code, notes, and snippets.

@stympy
Forked from therealadam/gist:731944
Created April 29, 2011 11:00
Show Gist options
  • Select an option

  • Save stympy/948168 to your computer and use it in GitHub Desktop.

Select an option

Save stympy/948168 to your computer and use it in GitHub Desktop.

Revisions

  1. @therealadam therealadam created this gist Dec 7, 2010.
    29 changes: 29 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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