rails - Redirecting console output to a file

A quick one-off solution:

irb:001> f = File.new('statements.xml', 'w')
irb:002> f << Account.find(1).statements.to_xml
irb:003> f.close

Create a JSON fixture:

irb:004> f = File.new(Rails.root + 'spec/fixtures/qbo/amy_cust.json', 'w')
irb:005> f << JSON.pretty_generate((q.get :customer, 1).as_json)
irb:006> f.close

You can use override $stdout to redirect the console output:

$stdout = File.new('console.out', 'w')

You may also need to call this once:

$stdout.sync = true

This will redirect all output to the file. If you want to temporarily redirect the output make sure that you store the original value of $stdout so you can change it back.


Apart from Veger's answer, there is one of more way to do it which also provides many other additional options.

Just open your rails project directory and enter the command:

rails c | tee output.txt

tee command also has many other options which you can check out by:

man tee

If you write the following code in your environment file, it should work.

if "irb" == $0
  config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))
end

You can also rotate the log file using

config.logger = Logger.new(Rails.root.join('path_to_log_file.txt'), number_of_files, file_roation_size_threshold)

For logging only active record related operations, you can do

ActiveRecord::Base.logger = Logger.new(Rails.root.join('path_to_log_file.txt'))

This also lets you have different logger config/file for different environments.