ActiveRecord::Subscriber
を使ってlogger
やBugsnagなどで通知するコードを書いたのでメモ。
lib/ext/active_record/slow_query_subscriber.rb
module Ext::ActiveRecord
class SlowQuerySubscriber < ActiveSupport::Subscriber
class SlowQuery < StandardError
end
cattr_accessor :threshold
def self.load!(threshold)
self.threshold = threshold
attach_to :active_record
end
def sql(event)
if event.duration > self.threshold
e = SlowQuery.new("Found slow query #{event.payload[:sql].inspect} : #{event.duration} msec > #{self.threshold} msec")
e.set_backtrace caller
ActiveRecord::Base.logger.warn(e.message)
Bugsnag.notify_or_ignore(e, severity: "warning", grouping_hash: event.payload[:sql], payload: event.payload, duration: event.duration)
end
end
end
end
使い方は以下
main.rb
# Detect slow query slower than 1000 msec
Ext::ActiveRecord::SlowQuerySubscriber.load!(1000)
slack-notifierなど使えば応用してSlack通知もできると思います。