我需要调试外部系统中的某些模块。该模块具有公共功能foo()
-如何知道位置(模块和功能名称)给定模块从哪个foo()调用?我的意思是一堆电话。
我无法停止系统,我可以通过重新加载此模块来完成所有工作(但带有一些调试信息)。
-module(given).
-export(foo/0).
foo() ->
%% here is my debug - and
%% i need here(!) known about unknown_module:unknown_foo!
ok.
---
-module(unknown_module).
..
unknown_foo() ->
given:foo(). %% see above
这是一个简单的把戏:
Trace = try throw(42) catch 42 -> erlang:get_stacktrace() end,
erlang:display(Trace)
这可能有效:
where_am_i() ->
try throw(a)
catch throw:a ->
erlang:get_stacktrace()
end.
除了它对于尾部呼叫不起作用。例如,给定这两个功能:
foo() ->
where_am_i().
bar() ->
X = where_am_i(),
{ok, X}.
我得到这些结果:
4> foo:foo().
[{foo,where_am_i,0},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_exprs,6},
{shell,eval_loop,3}]
5> foo:bar().
{ok,[{foo,where_am_i,0},
{foo,bar,0},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_exprs,6},
{shell,eval_loop,3}]}
即,我只能看到bar
,因为在调用foo
时已经离开了where_am_i
的调用框。
io:format(“〜s〜n”,[element(2,process_info(self(),backtrace))])。
self()可以由任何其他pid代替(rpc:pinfo甚至应与远程proc一起使用)。如果您甚至无法修改光源或光束,这将很有帮助。
这是我执行此操作的代码:
format_stack_entry(S) ->
{Module,Fun,Arity,[{file,File},{line,Line}]}=S,
io_lib:format("{~p,~p,~p,[{file,~p},{line,~p]}",[Module,Fun,Arity,File,Line]).
stacktop([Top|_]) ->
Top.
ancestor(N) ->
{_,Stacktrace}=erlang:process_info(self(),current_stacktrace),
ancestor(N+1,Stacktrace).
ancestor(1,S) ->
format_stack_entry(stacktop(S));
ancestor(N,[_|T]) ->
ancestor(N-1,T).
info(Format) -> io:format(lists:concat([ancestor(2),Format,"\r"])).
info(Format,Args) -> io:format(lists:concat([ancestor(2),Format,"\r"]),Args).
列表是系统中的自定义模块。请使用您的foo模块。