我想始终记录有关导致多线程ruby脚本崩溃的异常的尽可能多的信息。我知道有at exit
方法,可以在$!
require 'logger'
logger = Logger.new('logfile.log')
at_exit { logger.info "Exception that killed us is: #{$!}" }
threads =
10.times.with_object([]) do |_, t|
t << Thread.new { sleep 1 }
end
threads << Thread.new { raise RuntimeError, 'We died' }
threads.each(&:join)
但是,在日志中,它看起来像:
I, [2018-08-23T10:40:47.307841 #6772] INFO -- : Exception that killed us is: We died
是否可以向其中添加更多信息,例如回溯,文件和行号?
答案 0 :(得分:2)
回溯已包含文件和行号,$@
global包含回溯。
答案 1 :(得分:1)
对于以下异常消息,您也可以使用English based names:
require 'logger'
logger = Logger.new('logfile.log')
at_exit { logger.info "Exception that killed us is: #{$ERROR_INFO} - #{$ERROR_INFO.class} - #{$ERROR_POSITION}" }
threads =
10.times.with_object([]) do |_, t|
t << Thread.new { sleep 1 }
end
threads << Thread.new { raise RuntimeError, 'We died' }
threads.each(&:join)
请记住,$ERROR_INFO
在提供异常类本身时会为您提供异常消息。而$ERROR_INFO.class
为您提供异常类。对于您而言,$ERROR_INFO
将产生'We died'
。