In a rake task if I use puts command then I see the output on console. However I will not see that message in log file when app is deployed on production.
However if I say Rails.logger.info then in development mode I see nothing on console. I need to go to log file and tail that.
I would ideally like to use Rails.logger.info and in development mode inside the rake task, the output from logger should also be sent to console.
Is there a way to achieve that?
Code
For Rails 4 and newer, you can use Logger broadcast.
If you want to get both STDOUT and file logging for rake tasks in development mode, you can add this code into
config/environments/development.rb
:Test
Here's a small Rake task to test the above code :
Running
rake stdout_and_log:test
outputswhile
has been added to
log/development.log
.Running
rake stdout_and_log:test RAILS_ENV=production
outputswhile
has been added to
log/production.log
.Execute a background job with '&' and open script/console or whatever.. That way you can run multiple commands in the same window.
note Can get sloppy quickly when there is a lot of logging output.