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

pup*_*eno 58 ruby stack stack-trace

我需要在Ruby中获取堆栈跟踪对象; 不要打印它,只是为了让它做一些录音和倾倒以供以后分析.那可能吗?怎么样?

Sve*_*cke 79

您可以使用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"]
Run Code Online (Sandbox Code Playgroud)


小智 32

尝试

Thread.current.backtrace.join("\n")
Run Code Online (Sandbox Code Playgroud)


Nik*_*bak 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
Run Code Online (Sandbox Code Playgroud)

生产:

prog.rb:2:in `a'
prog.rb:6:in `b'
prog.rb:10
Run Code Online (Sandbox Code Playgroud)


Aje*_*i32 7

对于Ruby 2.0+,您可以使用Kernel#caller_locations.它基本上与Kernel#caller(在Sven Koschnicke的答案中涵盖)相同,除了不返回一个字符串数组,它返回一个Thread::Backtrace::Location对象数组.Thread::Backtrace::Location提供诸如,和等方法path,当您需要访问有关堆栈跟踪的特定详细信息而不仅仅是原始字符串时,这些方法可能很有用.linenobase_label

来自文档:

caller_locations(start = 1,length = nil)→array或nil

caller_locations(range)→array或nil

返回当前执行堆栈 - 包含回溯位置对象的数组.

有关Thread::Backtrace::Location更多信息,请参阅

可选的start参数确定从堆栈顶部省略的初始堆栈条目数.

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

返回nilif start大于当前执行堆栈的大小.

(可选)您可以传递一个范围,该范围将返回包含指定范围内的条目的数组.

用法示例:

def a
  caller_locations(0)
end
def b
  a
end
def c
  b
end

c.map(&:base_label)
#=> ["a", "b", "c", "<main>"]
Run Code Online (Sandbox Code Playgroud)


小智 7

Thread.current.backtrace
Run Code Online (Sandbox Code Playgroud)

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