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

> 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?

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.