投稿

ActiveRecordが発行するSQLをHookしたい

config/initializers/active_model_query_debug.rb

ActiveRecordが発行するSQLをHookしたい

ActiveRecordが実際に発行するSQLを、Railsの標準ログとは別に独自加工して出力したいときに使う。ActiveRecord::ConnectionAdapters::AbstractAdapterのlogメソッドをprependで上書きし、Model Load系のクエリだけを対象にログ出力する。ActiveRecordの内部APIに依存する実装のため、2020年時点の情報であり、Railsのバージョンによって挙動が変わる可能性がある。

解決

config/initializers/active_model_query_debug.rb

module ActiveModelQueryDebug
  def log(query, *args)
    # 'Model Load' are targeted
    if args.first&.end_with?("Load")
      Rails.logger.debug("query: #{query}")
    end

    super
  end
end

ActiveRecord::ConnectionAdapters::AbstractAdapter.prepend(ActiveModelQueryDebug)

動作

[1] pry(main)> User.first
query: SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
  User Load (1.3ms)  SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1

参考

active_record-sql_analyzer/sql_analyzer.rb at master · square/active_record-sql_analyzer