Putting It Together—Tracing Method Calls

Let’s work through a larger example. We want to write a module called Tracer. If we use Tracer in another module, entry and exit tracing will be added to any subsequently defined function. For example, given the following:

 defmodule​ Test ​do
 use​ Tracer
 def​ puts_sum_three(a,b,c), ​do​: IO.inspect(a+b+c)
 def​ add_list(list), ​do​: Enum.reduce(list, 0, &(&1+&2))
 end
 
 Test.puts_sum_three(1,2,3)
 Test.add_list([5,6,7,8])

we’d get this output:

 ==> call puts_sum_three(1, 2, 3)
 6
 <== returns 6
 ==> call add_list([5,6,7,8])
 <== returns 26

My approach to writing this kind of code is to start by exploring what we have to work with, and then to generalize. The goal is to metaprogram ...

Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.