Ruby on Rails

A lot times when you run rake tasks it would be nice to get output from rails logger into STDOUT. The simplest way to do it is to create a new rake task that will redirect output to STDOUT.

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

This way when you execute your rake task you can add verbose first to get stdout log messages or don’t include it to have messages sent to the default log file:

rake verbose [some_task]

Example output

Example output

Comments

coffeeandcode on August 05, 2016 15:25

It appears that the above code doesn't override the `logger` method inside of Rails models (and probably controllers & mailers). I changed the `verbose` task to the following and it works in Rails v4.2.6 (for models at least):```desc "Switch rails logger to stdout"task verbose: [:environment] do Rails.logger = ActiveRecord::Base.logger = Logger.new(STDOUT)end```

macbury on November 10, 2015 09:23

No, because ruby don`t share context

disqus_UDEtAVcr56 on November 10, 2015 09:22

Wouldn't that also effect your normal app logging if the app is running? I mean here we are not resetting logger back to its previous state.

enriquedelgado on September 30, 2015 20:52

How did you record that animated gif? Pretty cool :-]

jonyamo on December 17, 2014 01:30

Excellent information. Thank you for sharing!