How to get a stacktrace

My question is simple: When I perform an operation, I need to get a list of all the functions that get called during its execution.

For example:

function foo()
    ...
    rand(Int32)
end

function bar()
    foo()
end

What I want is something like:

julia> show_stacktrace(bar())
- Call to bar() with no arguments
- Call to foo() with no arguments
- Call to Base.rand(T::Type) with argument 'Int32'
- ...  # <- other calls within the Julia libraries

I’ve read the manual page of StackTraces but didn’t understand much. The examples in that page aren’t very clear and look different from what I want.
Thanks!

1 Like

The stacktrace should be obtained at the innermost point in the stack which you are interested in. Eg if you merely want to print,

@noinline function foo(x)
    show(STDOUT, MIME"text/plain"(), stacktrace())
    x + 1
end

@noinline bar(x) = foo(x + 2)

baz(x) = bar(x + 3)

baz(0)

shows

9-element Array{StackFrame,1}:
 foo(::Int64) at foo.jl:2                                     
 bar(::Int64) at foo.jl:6                                     
 baz(::Int64) at foo.jl:8                                     
 ....

Most of the complications in the example above are about pretty-printing and preventing inlining.

2 Likes

What if the innermost point is inside the Julia source code or an external package or something I can’t modify?

For example, for sort([1,3,2]) I want a list of all the functions called during the execution of Base.sort(v::AbstractArray).

Also, is it possible to show the arguments passed to them?

You would need to use a debugger, but that is work in progress at the moment:
https://github.com/Keno/ASTInterpreter2.jl
https://github.com/Keno/Gallium.jl

1 Like

You can try TraceCalls.jl. It doesn’t work super well with Base functions at the moment; for that you may wait for 0.7 and Cassette.jl.

2 Likes

are there any new approaches here on simply getting a non-interactive, non-intrusive function stack trace of a method call ?

4 Likes