Capturing warning messages

非 Y 不嫁゛ 提交于 2019-12-23 04:14:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!