Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 27 — Debugging & Tracing Techniques

Everything in this chapter exists in your Erlang world — dbg, tracing, Observer — but Elixir layers ergonomic front ends over them and adds a few tools of its own. The chapter is ordered by escalation: spy on values → stop execution → watch processes → trace the machine → profile it.

From Erlang you know: IO.inspect/1 is io:format("~p~n", _) that returns its argument, so it never disturbs the pipeline it sits in. dbg is the :dbg module you know, reachable without leaving Elixir. Observer is Observer.

27.1 Spying on Values: IO.inspect/2 and dbg/2

IO.inspect/2 returns its argument unchanged, which makes it a safe probe anywhere — including mid-pipeline:

[1, 2, 3]
|> IO.inspect(label: "before")
|> Enum.map(&(&1 * 2))
|> IO.inspect(label: "after")
|> Enum.sum()
before: [1, 2, 3]
after: [2, 4, 6]

binding() complements it inside functions — dump every variable at once:

def some_function(a, b, c) do
  IO.inspect(binding())   #=> [a: :foo, b: "bar", c: :baz]
end

dbg/1 (Elixir 1.14+) goes further: it prints the source expression, the file:line, and the value — and it understands pipelines, showing every step’s result:

__ENV__.file
|> String.split("/", trim: true)
|> List.last()
|> dbg()
[my_file.exs:5: (file)]
__ENV__.file #=> "/home/myuser/my_file.exs"
|> String.split("/", trim: true) #=> ["home", "myuser", "my_file.exs"]
|> List.last() #=> "my_file.exs"

Rule of thumb: IO.inspect for quick labels, dbg when you want the code next to the value. Neither requires a shell attached — both work in tests and logs.

27.2 Stop the World: Pry and Breakpoints

Pry — step in where dbg sits

Run your session with pry enabled:

iex --dbg pry          # plain iex
iex --dbg pry -S mix   # inside a project

Every dbg call now asks whether to stop execution. Accept, and you drop into IEx in the context of that code — all variables, imports, and aliases are reachable. Execution resumes with continue (c) or steps with next (n). The VM process handling your shell blocks while you pry; other processes keep running — isolation you already trust.

Breakpoints — no source edits

IEx.break!/2 sets a breakpoint on any compiled module, no code change:

IEx.break!(&MyApp.Accounts.find_user/1)        # stop once, on first call
IEx.break!(&MyApp.Accounts.find_user/1, 3)     # stops: fire 3 times, not a line
IEx.break!(MyApp.Accounts, :find_user, 1)      # module · function · arity
IEx.break!(MyApp.Accounts, :find_user, 1, 3)   # …with 3 stops

In the capture form the second argument is the number of stops — how many times the breakpoint fires, starting with the first call — not a line number. In the module form the third argument is the function’s arity and the fourth is the stop count, so {MyApp.Accounts, :find_user, 3} targets find_user/3, not “the third call”. Passing 3 hoping for line 3 is a genuinely confusing way to lose an afternoon. For a line, use IEx.break() inside the function body.

Once hit, you land in an IEx session with the arguments bound and can step line by line. Breakpoints have one limitation versus pry: no access to aliases/imports from the module’s source context.

Mix integrates breakpoints with tests directly:

# Debug all failed tests — breakpoint at each failing test's start
iex -S mix test --breakpoints --failed

# Debug the test at a specific file:line
iex -S mix test -b path/to/file:line

27.3 The IEx Session Is a Debugging Environment

An Erlang veteran keeps a ~/.erlang file; Elixir’s equivalent is .iex.exs in the project root — auto-loaded by every iex -S mix (or iex -S mix phx.server) start:

# .iex.exs
alias MyApp.Background.Worker, as: W
alias MyApp.Repo

import Ecto.Query

# one-off helper scripts for development — call YOUR app's real functions
defmodule FillData do
  def add_sample() do
    MyApp.Chat.create_room(%{name: "Hello room"})
    MyApp.Chat.add_members("hello", ["user_1", "user_2", "user_3"])
  end
end

# print long lists/maps without truncation
IEx.configure(inspect: [limit: :infinity])

Now in the shell: W.run(), FillData.add_sample(), Repo.all(...) — your whole app is one alias away while debugging.

Two more session conveniences worth installing as habits:

# persistent, searchable shell history (put in .bashrc/.zshrc)
export ERL_AFLAGS="-kernel shell_history enabled"
  • h Enum.map/2 — docs in-shell; h IEx.break! while learning this chapter.
  • respawn/0 — restart the shell inside the same node after you broke it, keeping the app and all processes alive.

27.4 Watching Processes: Observer

For system-level debugging, :observer beats every code-level tool:

iex -S mix phx.server
iex> :observer.start()

If Observer is missing in iex -S mix, ensure the application first:

Mix.ensure_application!(:observer)
:observer.start()

(Some package managers install a minimized Erlang without WX — install erlang-wx or the non-nox package. On headless machines — containers, K8s — connect from a graphical node and open Observer remotely against the target, exactly as you would with an Erlang distribution.)

Observer gives you: supervision tree walk, per-process state and mailbox length, ETS tables, memory breakdown, and the “trace” button that attaches live call traces to a chosen process.

Also available without any GUI — and on a container or K8s pod, where WX usually is not installed at all, these are what you actually reach for:

  • :observer_cli (Hex dependency) — a full supervision-tree browser in your terminal: :observer_cli.start(). The real Observer, text-mode.
  • :etop — a top-style process list: :etop.start(). Mailbox lengths and memory, sortable.
  • runtime_info/0 in IEx — mini dashboard, no dependency
  • Phoenix LiveDashboard — the web version, already mounted in generated Phoenix apps (Ch 10.7’s telemetry events feed it)

Prefer these over “connect from a graphical node” when the target is a container: they need no second machine and no WX.

27.5 Tracing: :sys.trace, :dbg, and recon

Trace one OTP process

Every gen_server/gen_statem process answers to sys — trace its message and callback flow live:

pid = Process.whereis(MyApp.Cache)
:sys.trace(pid, true)
# ...interact with the system...
:sys.trace(pid, false)

Output shows each receive, callback entry/exit, and reply — the fastest possible answer to “why is this GenServer behaving like that?”

Trace by pattern across the node — the :dbg module

The Erlang :dbg module needs no code changes and survives in any shell:

:dbg.tracer()
:dbg.tpl(MyApp.Accounts, :_, :_)   # all functions of the module
:dbg.p(:all, [:c])                 # trace calls from all processes

# ...reproduce the bug...

:dbg.stop_clear()                  # always clean up — tracing costs

Scope it down (:dbg.tp/3 on specific functions, [:c, :timestamp] flags) before aiming it at a busy node; broad traces on hot paths will flood the tracer process.

recon — production-safe inspection

The recon library is the community standard for poking running nodes safely:

# add {:recon, "~> 2.5"} to deps, then in the shell:

:recon_trace.calls({MyApp.Accounts, :_, :_}, 10)   # capped trace — auto-stops
:recon.proc_count(:memory, 10)                    # top 10 processes by memory
:recon.proc_count(:message_queue_len, 10)         # the mailbox-backlog hunt
:recon.info(Process.whereis(MyApp.Cache), :messages)

Note the module prefixes: recon is an Erlang library, so in Elixir it is :recon and :recon_trace. Bare recon.proc_count(...) raises UndefinedFunctionError — recon ships no delegating functions. The exception is Extrace (the Elixir wrapper, {:extrace, "~> 0.3"}), which does export Extrace.calls/2,3 and lets you write the bare calls.

:recon_trace.calls/2,3 refuses unlimited traces by design — a guardrail :dbg does not give you.

Telemetry and Logger (the framework layer)

  • Logger.debug/1 with config :logger, level: :debug when you need application-level breadcrumbs (levels compared via Logger.compare_levels/2).
  • Framework events ride :telemetry — Phoenix/Ecto emit spans at every boundary (§10.7); attach handlers or point LiveDashboard/Telemetry.Metrics at them before writing your own instrumentation.

27.6 When Config Lies: Debugging Compile-Time vs Runtime Configuration

A large class of “the code is right but behaves wrong” bugs is config read at the wrong time. Elixir splits configuration in two — and the split matches the compilation model of Ch 08:

flowchart LR
    CE["config.exs + dev/prod/test.exs<br/>COMPILE time — frozen into the build"] --> APP["application boots"]
    RE["runtime.exs<br/>RUN time — reads System.get_env"] --> APP
    APP --> RT["running node"]

Common failure modes and their probes:

SymptomLikely causeProbe
Release ignores env varsvalue baked into config.exs/prod.exsmove to runtime.exs
Test passes, prod crashestest.exs overrode the valueApplication.get_all_env(:my_app) in both
Value is nil in runtime.exsenv var not exported / wrong nameSystem.get_env("MEDIA_PATH") in iex on the target
Library sees stale valueit read config at compile timemove the read to runtime.exs, then read with Application.get_env/2 in init/1

The read-side functions tell you what the running node actually sees:

Application.get_env(:my_app, :media)        # value or nil — probe, don't fail
Application.fetch_env!(:my_app, :media)     # value or raises — contract
Application.compile_env(:my_app, :media)    # COMPILES the value in — do not
                                           # use to fix a stale-value bug; it
                                           # makes the freezing explicit, which
                                           # is only useful when compile-time
                                           # really is what you want
Application.get_all_env(:my_app)            # everything the node believes

Application.put_env(:my_app, :media, "/tmp/x")  # experiment in iex, no restart

For MIX_ENV experiments: MIX_ENV=prod mix phx.server compiles the prod path; confirm which file a value came from by temporarily setting it to a sentinel string and letting fetch_env! crash with it in hand.

27.7 Profiling and the Heavy Artillery

When tracing says where but not why, escalate:

ToolUse
mix profile.tprofstart here — time+memory, low overhead (OTP 27+)
mix profile.cprofcall counts only; legacy, superseded by tprof
mix profile.fprofexhaustive trace profile incl. GC; very slow
:crashdump_viewerGUI over erl_crash.dump files
microstate accounting (:msacc)where runtime threads spend their time
LTTng / DTrace / SystemTapOS-level tracers, per runtime_tools docs
Erlang in Anger (free ebook)the systematic playbook for sick nodes

Explore More

Checkpoint

  1. Why is IO.inspect/2 safe inside a pipeline while io:format is not?
  2. You need to trace all calls to MyApp.Worker.handle_info in production. Why :recon_trace.calls/3 rather than :dbg.p(:all, [:c])?
  3. A release ignores MEDIA_PATH. Give the two-minute diagnosis path.
  4. What can you reach in a pry session that breakpoints on compiled code cannot?
Answers
  1. It returns its argument — a probe, not a statement. io:format returns :ok, so splicing it into a pipeline changes the value that flows on.
  2. :recon_trace.calls/2,3 caps the number of trace messages and auto-stops — an unbounded :dbg.p/2 on a hot path can flood the tracer and degrade the node.
  3. Check where the value is read: runtime.exs (runs at boot, sees env vars) vs prod.exs (frozen at compile). On the target node: Application.get_all_env(:my_app) — if the key is stale or nil, the value was baked at build time; move it to runtime.exs and rebuild.
  4. Aliases and imports from the source file — pry compiles the snippet in the function’s lexical scope; breakpoints bind arguments only.

Next: Chapter 28 — LLM Integration & Agents — Part V is done; Ch 30 is the migration roadmap if you want practice first.