Krut
Krut

Reputation: 4220

How to log a map/struct in elixir

How do you log a map/struct type in ELixir without having to implement protocol String.Chars?

require Logger
Logger.debug  %{my: "map"}
** (Protocol.UndefinedError) protocol String.Chars not implemented for %{my: "map"}
    (elixir) lib/string/chars.ex:3: String.Chars.impl_for!/1
    (elixir) lib/string/chars.ex:17: String.Chars.to_string/1

Upvotes: 23

Views: 10454

Answers (2)

Prodis
Prodis

Reputation: 524

The Elixir way of writing arathunku's answer would be using the pipe syntax:

iex(3)> %{a: 1} |> inspect() |> Logger.debug()

23:20:30.265 [debug] %{a: 1}
:ok

Upvotes: 5

arathunku
arathunku

Reputation: 1159

You can use inspect/2 - https://hexdocs.pm/elixir/Kernel.html#inspect/2

It parses the data structure into an algebra document which can be printed with the logger.

iex(4)> Logger.debug inspect(%{a: 1})
08:47:32.776 [debug] %{a: 1}
:ok

Upvotes: 38

Related Questions