LoginSignup
15
14

More than 5 years have passed since last update.

ActiveRecordでSlowQueryを通知する方法

Last updated at Posted at 2016-02-08

ActiveRecord::Subscriberを使ってloggerBugsnagなどで通知するコードを書いたのでメモ。

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通知もできると思います。

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14