I need to get a stack trace object in Ruby; not to print it, just to get it to do some recording and dumping for later analysis. Is that possible? How?
A:
Try 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
produces:
prog.rb:2:in `a'
prog.rb:6:in `b'
prog.rb:10
Nikita Rybak
2010-09-30 09:01:36
I presume I'll have to throw an exception just to get the stack trace.
J. Pablo Fernández
2010-09-30 09:07:06
@J. Pablo Seems so. Post here if you find a way to get it directly.
Nikita Rybak
2010-09-30 09:11:08
Sven nailed it with Kernel.caller.
J. Pablo Fernández
2010-09-30 09:37:22
fuck you very much, downvoter
Nikita Rybak
2010-10-03 03:32:33
I'm not interested in exceptions, just in getting a stack trace.
J. Pablo Fernández
2010-09-30 09:37:03
+3
A:
You can use Kernel.caller for this. The same method is used when generating stack traces for exceptions.
From the docs:
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"]
Sven Koschnicke
2010-09-30 09:16:02