【问题标题】:Log exact exception origin and its backtrace at_exit in Ruby在 Ruby 中记录确切的异常来源及其在 at_exit 的回溯
【发布时间】:2019-01-29 12:48:20
【问题描述】:

我希望尽可能多地记录导致多线程 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

有没有办法在其中添加更多信息,例如回溯、文件和行号?

【问题讨论】:

    标签: ruby exception logging


    【解决方案1】:

    回溯已经包含文件和行号,$@ global 包含回溯。

    【讨论】:

      【解决方案2】:

      您也可以将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'

      【讨论】:

        猜你喜欢
        • 2010-12-03
        • 2010-09-18
        • 2014-09-11
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 2016-06-29
        • 1970-01-01
        • 2013-06-05
        相关资源
        最近更新 更多