Capturing STDOUT to a Logger

I’m using Test::Unit and i want to capture the console messages to a log
file - But im already using Logger to capture custom assertions,
messages etc. The problem with Logger as it is is that if an error
occurs in the script it doesn’t capture it as it will only grab things
explicitly sent to the logger (using Logger.info Logger.log etc.), and
not normal messages (puts, print etc.)

Is there a way that i can grab STDOUT and pipe it THROUGH the Logger?

I was thinking about putting a listener on the STDOUT stream that when a
line was writen out (through puts or print) could buffer it then call
Logger.info to write it out to the log file… I’m preaty new to Ruby so
i don’t even know if this is possible - Any ideas?

On Jun 15, 2006, at 6:50 PM, Brian C. wrote:

I was thinking about putting a listener on the STDOUT stream that
when a
line was writen out (through puts or print) could buffer it then call
Logger.info to write it out to the log file… I’m preaty new to
Ruby so
i don’t even know if this is possible - Any ideas?

Pick a level (#info, whatever)

logger = Logger.new …

def logger.puts(*s)
s.flatten.each { |item| info(item.to_s) }
end

$stdout = logger

rest of code

The other alternative is to set $stdout to your log file, e.g.

$stdout = File.open(“logfile.txt”, “w”)

then create the logger for stdout

logger = Logger.new($stdout)

This has it’s ups and its downs compared to the other method.

You don’t have to add an IO methods to the logger (puts, print, etc.)
but the stuff written won’t be prefixed with the log information.

Logan C. wrote:

The other alternative is to set $stdout to your log file, e.g.

$stdout = File.open(“logfile.txt”, “w”)

then create the logger for stdout

logger = Logger.new($stdout)

This has it’s ups and its downs compared to the other method.

You don’t have to add an IO methods to the logger (puts, print, etc.)
but the stuff written won’t be prefixed with the log information.

Thanks a million.

Just a quick note for anyone else, but it looks like Test::Unit actualy
writes directly to STDOUT (look at console/testrunner), he’s captured
STDOUT as a class viarable @io - so the only way that we can grab all
output (errors ect) is by manipulating STDOUT directly… so expanding
on the above method:

instead of

$stdout = File.open(“logfile.txt”, “w”)

use
STDOUT.reopen(“logfile.txt”, “w”)

then

logger = Logger.new($stdout)