TExcelTAD
Home › Elixir › Elixir Debugging

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:

elixir · try it yourself
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
elixir · try it yourself
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:

elixir · try it yourself
"  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:

elixir
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
text
$ 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:

elixir · try it yourself
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

  1. Read the whole error: Elixir messages are detailed and often suggest the fix.
  2. Look at the first line of the stack trace that points to your code.
  3. Add IO.inspect or dbg around the failing step and check your assumptions about the data's shape.
  4. Reproduce the problem in a small test or in IEx.
  5. Remove the debug prints before committing (mix credo can flag leftover IO.inspect and dbg calls).

Test yourself

Why can IO.inspect/2 be placed in the middle of a pipeline?

  1. It returns :ok
  2. It returns its argument unchanged
  3. It is ignored in pipelines
  4. It converts the value to a string

What does dbg/2 print for a pipeline?

  1. Only the final value
  2. The code and value of each step
  3. A stack trace
  4. Nothing outside IEx

Which function returns the current state of a GenServer for debugging?

  1. GenServer.state/1
  2. :sys.get_state/1
  3. Process.state/1
  4. IO.inspect(pid)