Nathaniel Waisbrot
Nathaniel Waisbrot

Reputation: 24513

Printing data in debugging context

I found Erlang's ~p format command helpful when debugging: it pretty-prints data into a form that can be round-tripped back into Erlang.

In Elixir, I can

require Logger
# ...
Logger.debug("foo=#{inspect foo} bar=#{inspect bar}")

and get the effect I want, but typing "inspect" everywhere is a pain and sometimes in my codebase I have to Kernel.inspect. I'd rather that it just did the right thing:

require Logger
# ...
Logger.debug("foo=#{foo} bar=#{bar}")

This doesn't work, because I get Elixir's notion of how to represent foo and bar in a UI -- atoms and (both kinds of) strings print the same, and maps throw an error instead of printing.

Can I tell Elixir to use Kernel.inspect as the default way it prints things?

Upvotes: 1

Views: 129

Answers (1)

Sort of... The way that "#{ foo }" works is that Elixir uses the String.Chars Protocol and the to_string implementation of that Protocol.

So, what you can do is

defimpl String.Chars, for: TypeOfFoo do

   def to_string(foo) do
      inspect( foo)
   end

end

So if foo is a Struct that you've defined somewhere, you can add this to the module you've defined it in. I'm not sure if the default implementations in the Elixir library for the standard types is overridable..

Upvotes: 1

Related Questions