Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log a map/struct in elixir

Tags:

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
like image 415
Krut Avatar asked Jan 26 '16 07:01

Krut


People also ask

How do you update a struct in Elixir?

In Elixir, structs can only ever have the keys that you assigned to it in the defstruct macro. You can use %{struct | key => value} just fine as long as the value of key is one of the keys that struct has.

How is struct Elixir defined?

To define a struct, the defstruct construct is used: iex> defmodule User do ...> defstruct name: "John", age: 27 ...> end. The keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they're defined in.


1 Answers

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
like image 181
arathunku Avatar answered Sep 18 '22 14:09

arathunku