tags:

views:

132

answers:

1

I have a small framework that is logging some info and debug messages using the Logger object built into ruby. At run time, this works great. At unit test time (using rspec if it matters...) i would like to dump the logged messages to an in memory string variable. What's the easiest way to go about doing this?

I was considering a monkey patch that would replace the info and debug methods, like this:


class Logger
  def info msg
    $logs = msg
    super msg
  end
end

is there a better way to go about sending my log messages to a string variable?

+7  A: 

Use StringIO

require 'stringio'
require 'logger'

strio = StringIO.new
l = Logger.new strio
l.warn "whee, i am logging to a string!"

puts strio.string
hrnt
Just remove the parentheses to have a rubyish style.
khelll
Parentheses removed. Personally, I prefer to use parenthesis, but I edited it to be more consistent with the coding style used in the question.
hrnt
thanks, hrnt. that's exactly what I was looking for!
Derick Bailey