Created
March 24, 2020 10:21
-
-
Save mriddle/bcc91f62f2b6946c8c0bfd07e3339bae to your computer and use it in GitHub Desktop.
Log slow queries in Rails
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
class QueryTracer < ActiveSupport::LogSubscriber | |
ACCEPT = %r{^(app|config|lib)}.freeze | |
FRAMES = 15 | |
THRESHOLD = 100 # 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