Skip to content

[rails] 在 Rails console 顯示 debug 訊息(如 SQL)

Published: at 03:38 AM (2 min read)

有時候在 Rails console 想要看到 debug 資訊,例如:

確認程式碼實際執行的 SQL 是什麼,有沒有 n+1 效能問題等等,但這樣的訊息似乎不是每次都會顯示

irb(main):003:0> Post.includes(:comments).limit(3)
  Post Load (4.6ms)  SELECT `posts`.* FROM `posts` LIMIT 3
  Comment Load (6.2ms)  SELECT `comments`.* FROM `comments` WHERE `comments`.`post_id` IN (1, 2, 3)
=>
[#<Post:0x0000000106918ca8 id: 1, title: "Post 1", body: nil, created_at: Sat, 20 Apr 2024 15:21:12.521294000 UTC +00:00, updated_at: Sun, 21 Apr 2024 14:04:08.304129000 UTC +00:00>,
 #<Post:0x0000000106918c08 id: 2, title: "Post 2", body: nil, created_at: Sat, 20 Apr 2024 15:21:12.594067000 UTC +00:00, updated_at: Sun, 21 Apr 2024 14:04:08.366316000 UTC +00:00>,
 #<Post:0x0000000106918ac8 id: 3, title: "Post 3", body: nil, created_at: Sat, 20 Apr 2024 15:21:12.616671000 UTC +00:00, updated_at: Sun, 21 Apr 2024 14:04:08.371338000 UTC +00:00>]

實際上在 Rails 中,有一個 config.log_level 設定,預設是 :debug,細節可以參考 官方文件

這個設定檔會在 /config/environments/#{env}.rb 中,例如預設在 production 環境

# Include generic and useful information about system operation, but avoid logging too much
# information to avoid inadvertent exposure of personally identifiable information (PII).
config.log_level = :info

這樣在 production 環境下,就不會顯示 debug 訊息,但在 development 環境下,預設是 :debug,所以會顯示上面的 SQL 或是更多的 debug 訊息

但更改這個設定檔,需要重新啟動 Rails server,如果你有需要在 runtime 更改 log level,可以在 Rails console 中執行以下程式碼 💁‍♂️

ActiveRecord::Base.logger = Logger.new(STDOUT)

Previous Post
[sidekiq] How to list Sidekiq jobs in the Rails console
Next Post
[rails] 在 Rails 更新了 asset stylesheet 或 javascript 但卻沒有更新