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

时间:2015-09-08 10:42:18

标签: ruby-on-rails logging activerecord

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

基本理念如下:

10:01:01 POST Load Executing "SELECT * from posts;'
10:01:03 POST Load 1712ms

如何配置Rails以将SQL登录分为两个步骤?

2 个答案:

答案 0 :(得分:3)

在执行之前,没有标准方法可以配置记录器输出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

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

User.find 1

将产生

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">

答案 1 :(得分:2)

我认为您正在搜索explain rails方法。所以,你需要实现类似的东西:

@query = Some.model.query
Rails.logger @query.explain
ActiveRecord::Base.silence do
  @query.load
end
Rails.logger "Finished"

当然,您可以添加定时器,原因,异常处理等。