Open In App

How to show Erlang call stack?

Last Updated : 24 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Erlang is a programming language that is well-suited for concurrent and distributed systems. One useful feature of Erlang is the ability to inspect the call stack, which is a record of the sequence of function calls that have led to the current point in the program’s execution. This can be helpful for debugging purposes, or for gaining a better understanding of the program’s flow.

In this article, we will look at how to show the Erlang call stack.

Method 1: Using ‘erlang:get_stacktrace/0’:

The erlang:get_stacktrace/0 function is a built-in function that returns a list of stack frames, representing the function calls that led to the current point in the program. Each stack frame is represented as a tuple with the following elements:

  1. {M, F, A}: M is the module name, F is the function name, and A is the arity of the function.
  2. Location: A tuple with information about the location of the function call in the source code. 

To show the call stack, you can simply call the function and print the returned list of stack frames.

StackTrace = erlang:get_stacktrace(),
io:format(“Call stack:~n”),
lists:foreach(fun(Frame) -> io:format(“~p~n”, [Frame]) end, StackTrace).

Note: Print each stack frame to the console using the io:format/2 function.

Method 2: Using the ‘dbg’ Module:

The ‘dbg‘ module is a built-in module that provides tools for debugging Erlang programs. One feature of the dbg module is the ability to start a tracer that will print the call stack every time a breakpoint is reached.

  • To start a tracer, you can use the ‘dbg:tracer/0‘ function. This will start a tracer that will print the call stack whenever a breakpoint is reached.
  • You can set breakpoints using the ‘dbg:p/2‘ function, which sets a breakpoint at a specific function in a specific module.

Example:

To set a breakpoint at the ‘foo/1’ function in the ‘my_module’ module, you can use the following code:

dbg:p(my_module, foo/1).

Once the tracer is started and the breakpoint is set, the call stack will be printed every time the ‘foo/1’ function is called.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads