Explain Codes LogoExplain Codes Logo

Disable Rails SQL logging in console

ruby
rails
sql
logging
Anton ShumikhinbyAnton Shumikhin·Dec 19, 2024
TLDR

To curb those chatty SQL outputs in Rails, up the ActiveRecord's logger to ERROR:

ActiveRecord::Base.logger.level = Logger::ERROR

This reins in the verbosity to focus mainly on errors.

How to temporarily disable SQL logging

When you need a temporary break from SQL logs—maybe for debugging—you can cocoon your code in a block:

ActiveRecord::Base.logger.silence do # Your noise-free operations end

This maneuver lets you enjoy quiet during operations and resume normal logs afterwards.

Resuming logging without a hitch

Here's how to get the logs back (spoiler alert: it's pretty straightforward):

old_logger = ActiveRecord::Base.logger # This is our trusty logger ActiveRecord::Base.logger = nil # Shush! We're doing science! # Silent operations go here... ActiveRecord::Base.logger = old_logger # Back to our regular programming

With this neat little trick, you can slip in and out of silence like a ninja.

Commanding the log level

Control the chatter with the logger's level:

ActiveRecord::Base.logger.level = Logger::INFO # or whatever level suits your mood.

Just like adjusting volume, but for logs.

Configuring the logger in development

In config/environments/development.rb, config.after_initialize provides a nifty handle for logging:

config.after_initialize do ActiveRecord::Base.logger = nil if Rails.env.development? # Developers deserve peace too! end

Think of it as a personal butler managing your logs.

Avoiding a null faux-pas

Setting the logger to nil might cause a mess; Rails can be a drama queen if expected items go missing. To avoid logger.warn errors:

ActiveRecord::Base.logger = Logger.new('/dev/null') # No logger no cry

This safely reroutes logs to the belly of the beast (i.e., Unix blackhole), keeping Rails drama-free.

Making ActiveSupport::LogSubscriber go stealth-mode

When subtlety is key, try overriding ActiveSupport::LogSubscriber. It's the SQL log raconteur that you never knew you could silence:

module ActiveSupport class LogSubscriber def debug(*args, &block) # Gags the SQL logging, effective silence ensues! end end end

Mum's the word!

Splitting the logger

If you need to see other ActiveRecord logs but keep SQL hushed, consider cloning the logger:

sql_silent_logger = ActiveRecord::Base.logger.clone ActiveRecord::Base.logger.level = Logger::ERROR # Mute SQL logs # Your operations go here... ActiveRecord::Base.logger = sql_silent_logger # Back to the reality show

With this, SQL logs can take a nap while the rest of the logs party on!

Disabling SQL logging in Rails 4

In Rails 4, disabling SQL logging is a breeze:

config.active_record.logger = nil # Rails 4's gift to mankind

The SQL gods can finally rest...