Elixir Debugging
Elixir has excellent tools for finding out what your code is doing, from a quick print to inspecting a running production system. This lesson covers the ones you will use daily.
IO.inspect
IO.inspect/2 prints a value and returns it unchanged, so it can be dropped anywhere, especially into pipelines. Use label: to tell the outputs apart:
order = %{items: [%{sku: "A1", qty: 2, price: 9.5}, %{sku: "B7", qty: 1, price: 30.0}], discount: 0.1}
total =
order.items
|> Enum.map(&(&1.qty * &1.price))
|> IO.inspect(label: "line totals")
|> Enum.sum()
|> IO.inspect(label: "subtotal")
|> Kernel.*(1 - order.discount)
|> IO.inspect(label: "after discount")
IO.puts("Total: #{Float.round(total, 2)}")line totals: [19.0, 30.0]
subtotal: 49.0
after discount: 44.1
Total: 44.1
Useful options:
| Option | Effect |
|---|---|
label: "x" |
prefix the output |
limit: :infinity |
print all elements (default limit is 50) |
pretty: true, width: 40 |
pretty-print over several lines |
charlists: :as_lists |
show [7, 8] instead of ~c"\a\b" |
structs: false |
show a struct as a plain map |
data = %{name: "sensor-7", readings: Enum.to_list(1..12), tags: [:indoor, :lab]}
IO.inspect(data, pretty: true, width: 30, limit: 5)
IO.inspect([7, 8, 9], charlists: :as_lists)%{
name: "sensor-7",
readings: [1, 2, 3, ...],
...
}
[7, 8, 9]
limit: also applies to the entries of a map, which is why tags was replaced by ....
dbg
dbg/2 (Elixir 1.14+) prints the code together with its value. Given a pipeline, it shows the result of every step:
" The Quick Brown Fox "
|> String.trim()
|> String.downcase()
|> String.split()
|> Enum.map(&String.capitalize/1)
|> dbg(syntax_colors: [])
discount = 0.15
dbg(round(200 * (1 - discount)), syntax_colors: [])[/w/main.exs:6: (file)]
" The Quick Brown Fox " #=> " The Quick Brown Fox "
|> String.trim() #=> "The Quick Brown Fox"
|> String.downcase() #=> "the quick brown fox"
|> String.split() #=> ["the", "quick", "brown", "fox"]
|> Enum.map(&String.capitalize/1) #=> ["The", "Quick", "Brown", "Fox"]
[/w/main.exs:9: (file)]
round(200 * (1 - discount)) #=> 170
In a terminal dbg colours its output; syntax_colors: [] turns that off so the text above stays plain. If you start IEx with iex --dbg pry (Elixir 1.17+; in 1.14–1.16 this was the default inside IEx), dbg instead stops execution and opens an interactive prompt at that point.
IEx.pry and breakpoints
In IEx you can stop inside a running function:
defmodule Cart do
def total(items) do
require IEx
IEx.pry() # execution stops here when running under IEx
Enum.sum(Enum.map(items, & &1.price))
end
end$ iex -S mix
iex> Cart.total([%{price: 3}])
Break reached: Cart.total/1 (lib/cart.ex:4)
pry(1)> items
[%{price: 3}]
pry(2)> continue()break!(Cart, :total, 1) in IEx sets a breakpoint without editing the file.
Inspecting processes
Every process can be examined while it runs. Process.info/2 and :sys.get_state/1 are invaluable for GenServers:
defmodule Basket do
use GenServer
def start_link(_), do: GenServer.start_link(__MODULE__, [], name: __MODULE__)
def add(item), do: GenServer.cast(__MODULE__, {:add, item})
@impl true
def init(items), do: {:ok, items}
@impl true
def handle_cast({:add, item}, items), do: {:noreply, [item | items]}
end
{:ok, pid} = Basket.start_link([])
Basket.add("tea")
Basket.add("scones")
IO.inspect(:sys.get_state(Basket))
IO.inspect(Process.info(pid, :registered_name))
IO.inspect(Process.info(pid, :message_queue_len))["scones", "tea"]
{:registered_name, Basket}
{:message_queue_len, 0}
:sys.get_state/1 sends a system message, which the server handles after the two casts, so the state already contains both items. A growing message_queue_len is a classic sign of an overloaded process.
More tools
| Tool | What it's for |
|---|---|
:observer.start() |
GUI showing processes, memory, supervision trees, ETS tables |
:sys.trace(pid, true) |
print every message a GenServer receives |
Logger.debug/1, Logger.info/1 |
structured logging with levels and metadata |
:recon (library) |
safe production diagnostics |
mix test --trace, mix test --failed |
run tests one at a time / only the failed ones |
| ElixirLS / Lexical / Expert (editors) | breakpoints and step debugging in VS Code and others |
A debugging checklist
- Read the whole error: Elixir messages are detailed and often suggest the fix.
- Look at the first line of the stack trace that points to your code.
- Add
IO.inspectordbgaround the failing step and check your assumptions about the data's shape. - Reproduce the problem in a small test or in IEx.
- Remove the debug prints before committing (
mix credocan flag leftoverIO.inspectanddbgcalls).
Test yourself
Why can IO.inspect/2 be placed in the middle of a pipeline?
- It returns
:ok - It returns its argument unchanged
- It is ignored in pipelines
- It converts the value to a string
What does dbg/2 print for a pipeline?
- Only the final value
- The code and value of each step
- A stack trace
- Nothing outside IEx
Which function returns the current state of a GenServer for debugging?
GenServer.state/1:sys.get_state/1Process.state/1IO.inspect(pid)