DEV Community

mreigen
mreigen

Posted on • Originally published at mreigen.Medium

Elixir: Handy debug chain-able pretty-print function

I picked up Elixir last year at work. While some debugging tools are good to casual debug things in Elixir, IO.puts/2 and IO.inspect/2 are sometimes much faster to show what I wanted to see in the console log output.

The drawback of IO.puts/2 is that it can only take a strings. It will fail if you pass in anything else, try a map or list! Using IO.inspect/2 is nice and all but I found that a lot of times the output just got lost in the logs.

I came up with a simple way to format the output so that it could be found easily in the logs by giving it a different color than the typical green or blue output text and set a label to each output so that in the cases I have more than one output at a time, I would know which one is for which.

In the example below, you can see how simple it is to use. I’m using it with a map in this case. I named the function D.pp\2 (in the D module in my project by the way.)

Alt Text

As you can see it returns the map to be chained:

%Membership{}
|> changeset(params)
|> put_assoc(:stakeholders, [])
|> D.pp("Changeset after put assocs stakeholders") #<-------
|> touch(user)
|> Repo.insert()
Enter fullscreen mode Exit fullscreen mode

In the example above, D.pp/2 is put in between the pipes to show the value of the changeset after put_assoc so I could see what is the changeset value at that exact point, and wouldn’t mess up the data in the workflow.

Or I could use it in tests:

response = build_conn()
|> as_user(context.regular)
|> get(context.path)
|> D.pp("after get") #<--------
|> json_response(200)
|> D.pp("received response") #<---------
Enter fullscreen mode Exit fullscreen mode

Here is the function!

def pp(what_to_print, debug_message \\ "") do
  IO.puts("#{IO.ANSI.yellow()} START #{debug_message} ====================")
  IO.puts(IO.ANSI.yellow() <> inspect(what_to_print, pretty: true, limit: :infinity))
  IO.puts("#{IO.ANSI.yellow()} END   #{debug_message} ====================\n\n")
  what_to_print
end
Enter fullscreen mode Exit fullscreen mode

Maybe the next step is to create its own module and allow users to configure settings for each project for color, infinity limit, etc…? You can simply put this in your project in a module named D or Debug and call it like how I call it D.pp

Please let me know in the comment if you have any question and if you find it useful in your project, please help me out by letting me know here, mention me somewhere and/or hit that love button! Thank you.

Top comments (0)