Elixir 1.14 introduced the dbg/2
function, which inspects and prints a passed value.
It also adds the curent location to the log output, which is useful for finding the debug statement later.
dbg(~N[2000-01-01 23:00:07.123])
[lib/phoenix_example_web/controllers/page_controller.ex:10: PhoenixExampleWeb.PageController.home/2] ~N[2000-01-01 23:00:07.123] #=> ~N[2000-01-01 23:00:07.123]
The dbg/2
function prints the code passed to it, which is especially useful when adding it to a pipeline, where it will show the return values of each item:
~N[2000-01-01 23:00:07.123] |> NaiveDateTime.truncate(:second) |> NaiveDateTime.to_iso8601() |> dbg()
[lib/phoenix_example_web/controllers/page_controller.ex:10: PhoenixExampleWeb.PageController.home/2] ~N[2000-01-01 23:00:07.123] #=> ~N[2000-01-01 23:00:07.123] |> NaiveDateTime.truncate(:second) #=> ~N[2000-01-01 23:00:07] |> NaiveDateTime.to_iso8601() #=> "2000-01-01T23:00:07"
Printing the location already makes it a good replacement for IO.inspect/2
, but the dbg/2
function also starts the debugger when in an IEx shell:1
Request to pry #PID<0.625.0> at PhoenixExampleWeb.PageController.home/2 (lib/phoenix_example_web/controllers/page_controller.ex:7) 4: def home(conn, _params) do 5: 6: 7: ~N[2000-01-01 23:00:07.123] 8: |> NaiveDateTime.truncate(:second) 9: |> NaiveDateTime.to_iso8601() 10: |> dbg() Allow? [Yn]
This works with Phoenix applications as well, if they’re started with an attached IEx shell:
iex -S mix phx.server