umar
umar

Reputation: 4389

How to capture output produced with 'puts' inside a script and save it to a file in ruby/rails?

From my script/ directory in a rails app, I am trying to capture the output produced from a lib file and instead of displaying it on the screen, i want it to be saved to a file. I have a script that should display output to screen when it calls "puts" but before calling a method that produces output, it should set something so that the function called should log to a file when it uses puts. I have been experimenting withe the following two files in my rails application but they do not seem to work. (The stderr output is captured to the file correctly, but the otuput produced from a simple call to "puts" is not saved to the file "a.log" in the following code:)

#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require File.join(RAILS_ROOT, 'lib/mylogger.rb')

puts "logtest" # should output logtest on the screen

STDERR.puts "logtest" # should also output on the screen

x = STDOUT
y = STDERR
STDOUT = File.new("a.log", "w")
STDERR = File.new("b.log", "w")
m = MyLogger.new
m.run
STDOUT = x
STDERR = y
puts "logtest" # should log to the screen
STDERR.puts "logtest" # should log to the screen

and the mylogger.rb file is as follows:

class MyLogger

  def run
    1.upto 1_000_000 do |x|
      puts "mylogger #{x}" # should log to the file a.log, this does not work
      STDERR.puts "mylogger #{x}" # should log to the file b.log, this works
    end
  end
end

Upvotes: 1

Views: 691

Answers (2)

umar
umar

Reputation: 4389

I changed the line

STDOUT = File.new("a.log", "w")

to

$stdout = File.new("a.log", "w")

and i changed

STDOUT = x

to

$stdout = STDOUT

and it worked

Upvotes: 0

npj
npj

Reputation: 108

$stdout.reopen(File.open("a.log", "w"))

Upvotes: 3

Related Questions