Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Send logger messages to a string variable?

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?

like image 892
Derick Bailey Avatar asked Sep 27 '09 18:09

Derick Bailey


1 Answers

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
like image 66
hrnt Avatar answered Nov 08 '22 09:11

hrnt