更改rails ActiveRecord 查询跟踪的格式

问题描述 投票:0回答:1

在我使用 Postgres 的 Ruby on Rails 项目中,当触发查询时,我会在 Rails 日志中看到这一点。

 MessageThreadsUser Count (2.0ms)  SELECT COUNT(*) FROM "message_threads_users" WHERE "message_threads_users"."received_unread_at" IS NOT NULL AND "message_threads_users"."user_id" = $1 /*controller='users',action='check_unread'*/  [["user_id", 111]]

我希望它向我展示这个:

 MessageThreadsUser Count (2.0ms)  SELECT COUNT(*) FROM "message_threads_users" WHERE "message_threads_users"."received_unread_at" IS NOT NULL AND "message_threads_users"."user_id" = 111 /*controller='users',action='check_unread'*/ 

我怎样才能实现这个目标?

ruby-on-rails ruby
1个回答
0
投票

要在 Rails 日志中获得所需的输出,您可以通过覆盖 Rails 应用程序中的

ActiveRecord::Base.logger
配置来自定义 SQL 日志记录格式。以下是如何修改它以显示 SQL 查询,并将占位符替换为实际值:

# config/environments/development.rb

Rails.application.configure do
  # Other configurations...

  # Customize ActiveRecord SQL logging format
  config.active_record.logger = Logger.new(STDOUT, formatter: proc { |severity, datetime, progname, msg|
    if msg.start_with?("  SQL")
      # Replace the placeholder with the actual value
      msg.gsub(/\$\d+/) { |match| match[1..].to_i }
    else
      "#{msg}\n"
    end
  })
end

我能想到的一种方法是使用此配置更改配置,Rails 日志中的 SQL 查询将显示实际值而不是占位符。确保将此配置放入适当的环境文件中(例如,

config/environments/development.rb
表示开发环境)。

现在,当您在开发模式下运行 Rails 应用程序时,您应该在日志中看到带有实际值而不是占位符的 SQL 查询。

© www.soinside.com 2019 - 2024. All rights reserved.