Beautiful Erlang - The Print Macro

January 13, 2011


Debugging an Erlang application can be… challenging. Often the best bug squashing weapon in the toolbox is to simply print a variable to the console.

At minimum, it looks something like this:

io:format("MyValue: ~p~n", [MyValue])

This prints:

MyValue: value

That’s a lot of effort for very negligible results. After a few intense debugging sessions, all of that typing will make your fingers will fall off.

I’d like my fingers to stay where they are, so I make life easier by including the following macro definition in every Erlang application that I create:

-ifndef(PRINT).
-define(PRINT(Var), io:format("DEBUG: ~p:~p - ~p~n~n ~p~n~n", [?MODULE, ?LINE, ??Var, Var])).
-endif.

This allows me to write:

?PRINT(MyValue)

Which prints the module name, line number, variable name, and variable value as follows:

DEBUG: module_name:80 - MyValue
value

The macro actually accepts any Erlang term. For example:

?PRINT({this_is_myvalue, MyValue}).

Causes the system to print:

DEBUG: module_name:80 - {this_is_myvalue, MyValue}
{this_is_myvalue, value}

This considerably shortens the amount of typing necessary to inspect a variable. In addition, the macro name gives me a distinctive token to search for to quickly locate debug statements.

The macro uses a few special variables:

« Back