代码之家  ›  专栏  ›  技术社区  ›  Pablo Fernandez

如何在Ruby中获取堆栈跟踪对象?

  •  55
  • Pablo Fernandez  · 技术社区  · 13 年前

    我需要在Ruby中获得一个堆栈跟踪对象;不需要打印它,只需要让它做一些记录和转储,以便以后进行分析。有可能吗?怎么用?

    6 回复  |  直到 7 年前
        1
  •  79
  •   Uri Agassi    10 年前

    你可以使用 Kernel.caller 为此。为异常生成堆栈跟踪时使用相同的方法。

    来自文档:

    def a(skip)
      caller(skip)
    end
    def b(skip)
      a(skip)
    end
    def c(skip)
      b(skip)
    end
    c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"]
    c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"]
    c(2) #=> ["prog:8:in `c'", "prog:12"]
    c(3) #=> ["prog:13"]
    
        2
  •  29
  •   Alex Bondar    11 年前

    尝试

    Thread.current.backtrace.join("\n")
    
        3
  •  12
  •   Andrew Grimm atk    13 年前

    尝试 error.backtrace :

    # Returns any backtrace associated with the exception.  
    # The backtrace is an array of strings, each containing either ``filename:lineNo: in `method’’’ or ``filename:lineNo.’‘
    
    def a
      raise "boom"
    end
    
    def b
      a()
    end
    
    begin
      b()
    rescue => detail
      print detail.backtrace.join("\n")
    end
    

    生产:

    prog.rb:2:in `a'
    prog.rb:6:in `b'
    prog.rb:10
    
        4
  •  7
  •   Community Egal    7 年前

    对于Ruby 2.0+,您可以使用 Kernel#caller_locations . 基本上与 Kernel#caller (覆盖) Sven Koschnicke's answer ,除了返回字符串数组之外,它还返回 Thread::Backtrace::Location 物体。 线程::回溯::位置 提供方法,例如 path , lineno base_label 当您需要访问有关堆栈跟踪的特定细节,而不仅仅是原始字符串时,这可能非常有用。

    the docs :

    呼叫者位置(开始=1,长度=nil)数组或nil

    呼叫者位置(范围)数组或零

    返回当前执行堆栈“包含回溯的数组” 定位对象。

    线程::回溯::位置 更多信息。

    可选的start参数决定初始堆栈的数目。 要从堆栈顶部省略的项。

    第二个选项 length 参数可用于限制 从堆栈返回条目。

    退换商品 nil 如果 start 大于当前执行的大小 栈。

    或者,您可以传递一个范围,该范围将返回一个包含 指定范围内的条目。

    使用实例:

    def a
      caller_locations(0)
    end
    def b
      a
    end
    def c
      b
    end
    
    c.map(&:base_label)
    #=> ["a", "b", "c", "<main>"]
    
        5
  •  3
  •   Rajat Bansal    7 年前
    Thread.current.backtrace
    

    这将为您提供一个数组,其中包含任何正常回溯中可能得到的所有行。

        6
  •  2
  •   Sammy Larbi    12 年前

    如果你想的话,你也可以自己创造。如中所示 雄辩红宝石 Russ Olsen:

    # define a proc to use that will handle your trace 
    proc_object = proc do |event, file, line, id, binding, klass| 
      puts "#{event} in #{file}/#{line} #{id} #{klass}"
    end 
    
    # tell Ruby to use your proc on traceable events
    set_trace_func(proc_object)