Rails日志:只在日志中显示Create、Update和Destroy SQL语句,而不显示其他语句



我只想在日志中看到CREATE/UPDATE/DESTROY相关的sql语句。我不希望在日志中显示任何与READ相关的语句、缓存或任何其他信息,因为这会使筛选变得困难。

目前在app/config/environments/production.rb中,我有以下配置集,它在日志中显示得太多了:

config.log_level = :debug

生产的默认配置显示的信息太少。它忽略了我想看到的所有sql语句:

# shows too little information
config.log_level = :info

rails中是否有一个配置设置,使日志只输出我想看到的信息?如果没有:我该怎么做?

您可以通过将log_level设置为:info来禁用ActiveRecord数据库查询的日志记录。

然后使用Rails的ActiveSupport::Instrumentation并订阅sql.active_record事件。

只需将以下代码添加到初始值设定项中:

# in `config/initializers/query_logger.rb`
class QueryLogger
  def call(name, started, finished, unique_id, payload)
    query = payload[:sql]
    Rails.logger.info("SQL Query: #{query}") unless query.start_with?('SELECT')
  end
end
ActiveSupport::Notifications.subscribe('sql.active_record', QueryLogger.new)

最新更新