Skip to content

Instantly share code, notes, and snippets.

@jameslafa
Created July 11, 2016 12:58
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jameslafa/c03f09784b0a24531be43dd9250d2fd5 to your computer and use it in GitHub Desktop.
Save jameslafa/c03f09784b0a24531be43dd9250d2fd5 to your computer and use it in GitHub Desktop.
Easily debug rake task
desc "switch rails logger to stdout"
task :verbose => [:environment] do
Rails.logger = Logger.new(STDOUT)
end
desc "switch rails logger log level to debug"
task :debug => [:environment, :verbose] do
Rails.logger.level = Logger::DEBUG
end
desc "switch rails logger log level to info"
task :info => [:environment, :verbose] do
Rails.logger.level = Logger::INFO
end
@jameslafa
Copy link
Author

Add debug.rake in /lib/tasks/debug.rake.

Calling rake debug my_task switch automatically the log level to debug and output in the console.

@repoles
Copy link

repoles commented Jan 9, 2020

Clever! Tks ;)

@gbs4ever
Copy link

gbs4ever commented Nov 6, 2020

very cool

@repoles
Copy link

repoles commented Mar 2, 2023

On the initialization, Rails stores a logger instance reference in Rails.logger and also in some other places, like ActiveRecord::Base.logger, ActiveJob::Base.logger, etc. It is the same object referenced in different locations.

Rails.logger == ActiveRecord::Base.logger # => true

Better than create a new logger like in line 3 of debug.rake would be change the existing object output to STDOUT. It is possible to accomplish that using the logger reopen method. Like this:

Rails.logger.reopen(STDOUT)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment