如何在Rails查询发生之前记录它们?

mah*_*off 8 logging activerecord ruby-on-rails

默认情况下,Rails记录器将在执行后显示SQL.有时 - 主要是在查询需要很长时间时 - 我想配置记录器在执行之前输出SQL.然后,一旦数据库响应,它就可以添加后续日志.

基本想法是这样的:

10:01:01 POST Load Executing "SELECT * from posts;'
10:01:03 POST Load 1712ms
Run Code Online (Sandbox Code Playgroud)

如何配置Rails以将SQL登录分成两个这样的步骤?

dim*_*ura 5

没有标准方法可以配置记录器在执行输出 SQL 查询。

但您仍然可以通过扩展ActiveRecord::LogSubscriber类以这种方式记录查询。

# initializers/extensions/active_record_logger.rb
module Extensions
  module ActiveRecordLogger
    IGNORE_PAYLOAD_NAMES = ActiveRecord::LogSubscriber::IGNORE_PAYLOAD_NAMES

    # ActiveRecord::LogSubscriber doesn't implement this method.
    # This method will be invoked before event starts processing.
    # It's exactly we are looking for!
    def start(name, id, payload)
      super

      return unless logger.debug?
      return if IGNORE_PAYLOAD_NAMES.include?(payload[:name])

      name = payload[:name]
      sql = payload[:sql]

      name = color(name, nil, true)
      sql  = color(sql, nil, true)

      debug "STARTING #{name}  #{sql}"
    end
  end
end

ActiveRecord::LogSubscriber.include Extensions::ActiveRecordLogger
Run Code Online (Sandbox Code Playgroud)

现在您将在执行前获取查询日志。例如,查询

User.find 1
Run Code Online (Sandbox Code Playgroud)

将产生

STARTING  User Load  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1
User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
#<User id: 1, username: "dimakura", created_at: "2015-09-08 13:16:42", updated_at: "2015-09-08 13:16:42">
Run Code Online (Sandbox Code Playgroud)