问题
Is there a way to capture the warnings, something like rescue for exceptions? I do not want to simply disable the warnings (by doing $VERBOSE = nil
) but want to capture the content of the warning messages during run time.
回答1:
You can redirect stderr
to a StringIO object to capture the warnings output in a string:
require 'stringio'
old_stderr = $stderr
$stderr = StringIO.new
Foo = 1
Foo = 2 # generates a warning
puts $stderr.string # prints the warning
$stderr = old_stderr
回答2:
require 'stringio'
def capture_stderr
old, $stderr = $stderr, StringIO.new
result = yield
[result, $stderr.string]
ensure
$stderr = old
end
回答3:
This is kinda ugly because you will be writing to files and you might not have permission to write to them, and it will hide ALL output to $stderr
, not just the warnings, but it works:
$stderr.reopen("errors.txt")
MyConst = 4
MyConst = 5 # generates a warning on the standard error output
$stderr.reopen("errors2.txt")
puts "The following errors happened:"
puts File.read("errors.txt")
来源:https://stackoverflow.com/questions/12761995/capturing-warning-messages