Erlang调试工具 #

一、Debugger #

1.1 启动Debugger #

erlang
debugger:start().

1.2 设置断点 #

在Debugger界面中:

  1. 选择模块
  2. 设置断点行
  3. 运行到断点

1.3 命令行调试 #

erlang
-module(debug_example).
-export([demo/0]).

demo() ->
    io:format("Step 1~n"),
    X = 1 + 1,
    io:format("X = ~p~n", [X]),
    Y = X * 2,
    io:format("Y = ~p~n", [Y]),
    Y.

二、Observer #

2.1 启动Observer #

erlang
observer:start().

2.2 功能 #

  • 进程监控
  • 内存使用
  • 应用信息
  • 表信息
  • 系统信息

2.3 命令行替代 #

erlang
-module(observer_cli).
-export([processes/0, memory/0]).

processes() ->
    io:format("Process count: ~p~n", [erlang:system_info(process_count)]).

memory() ->
    io:format("Memory: ~p~n", [erlang:memory()]).

三、调试技巧 #

3.1 io:format调试 #

erlang
-module(io_debug).
-export([process/1]).

process(Data) ->
    io:format("Input: ~p~n", [Data]),
    Result = transform(Data),
    io:format("Output: ~p~n", [Result]),
    Result.

transform(D) -> D.

3.2 dbg模块 #

erlang
-module(dbg_debug).
-export([demo/0]).

demo() ->
    dbg:tracer(),
    dbg:p(all, c),
    dbg:tpl(lists, map, x),
    lists:map(fun(X) -> X * 2 end, [1, 2, 3]),
    dbg:stop().

3.3 IEx.pry(Elixir风格) #

erlang
-module(pry_debug).
-export([demo/0]).

demo() ->
    X = 10,
    io:format("Before pry: ~p~n", [X]),
    X.

四、性能分析 #

4.1 fprof #

erlang
-module(fprof_example).
-export([demo/0]).

demo() ->
    fprof:apply(fun slow_function/0, []),
    fprof:profile(),
    fprof:analyse().

slow_function() ->
    lists:seq(1, 10000).

4.2 eprof #

erlang
-module(eprof_example).
-export([demo/0]).

demo() ->
    eprof:start(),
    eprof:profile([self()], fun slow_function/0, []),
    eprof:stop_profiling(),
    eprof:analyze(),
    eprof:stop().

slow_function() ->
    lists:seq(1, 10000).

4.3 cprof #

erlang
-module(cprof_example).
-export([demo/0]).

demo() ->
    cprof:start(),
    slow_function(),
    cprof:pause(),
    cprof:analyse(),
    cprof:stop().

slow_function() ->
    lists:seq(1, 10000).

五、总结 #

本章学习了:

  • Debugger使用
  • Observer使用
  • 调试技巧
  • 性能分析
最后更新:2026-03-27