Erlang/OTP: simple process debugging with sys module (Part 1)

The module sys contains functions for simple debugging of processes implemented using behaviours. So for processes which are gen_server, gen_fsm, gen_event or supervisor, we can directly use sys functions to get simple debugging information. The functions are:

%% Name is the process pid or local name or global name
%% Flag is true, turn on log; Flag is print, print out all the collected logs on stdio
log(Name, Flag) -> ok | {ok, [system_event()]}
log(Name, Flag, Timeout) -> ok | {ok, [system_event()]}

%% Flag is true, turn on statistics; Flag is get, return all the Statistics collected
statistics(Name, Flag) -> ok | {ok, Statistics}
statistics(Name, Flag, Timeout) -> ok | {ok, Statistics}

%% Flag is true, turn the trace, the different between trace and log is that trace/2 prints system events on stdio
%% but logs are stored in debug structure, which cat be printed out later
trace(Name, Flag) -> ok
trace(Name, Flag, Timeout) -> ok

For example, a example gen_server, we want to check the calls & returns to it,

-module(example_server).
-behaviour(gen_server).
-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-record(state, {}).
start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
init([]) ->
    {ok, #state{}}.
handle_call(hello, _From, State) ->
    {reply, {ok, world}, State};
handle_call(_Request, _From, State) ->
    {reply, unknown_cmd, State}.
handle_cast(_Msg, State) ->
    {noreply, State}.
handle_info(_Info, State) ->
    {noreply, State}.
terminate(_Reason, _State) ->
    ok.
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.

On Erlang terminal, we can get the information:

5> example_server:start_link()
5> .
{ok,<0.44.0>}
6> sys:log(example_server, true).
ok
7> gen
gen           gen_event     gen_server
7> gen_server:call(example_server, hello).
{ok,world}
8> sys:log(example_server, print).
*DBG* example_server got call hello from <0.33.0>
*DBG* example_server sent {ok,world} to <0.33.0>, new state {state}
ok