简体   繁体   中英

elixir Logger for lists, tuples, etc

I can use the elixir logger for inspecting strings

 > str = "string"
 > Logger.info "Here is a #{str}"
 [info] Here is a string

But when I log a list, it doesn't look pretty

 > list = [1,2,3,4,5]
 > Logger.info "Here is a list: #{list}"
 [info] Here is a list: ^A^B^C^D^E^F

When I log keyword list, it errors

 > kwl = [a: "apple", b: "banana"]
 > Logger.info "Here is a keyword list: #{kwl}"
   ** (ArgumentError) argument error
   (stdlib) :unicode.characters_to_binary([a: "apple", b: "banana"])
   (elixir) lib/list.ex:555: List.to_string/1

How do you logger lists, tuples and data types other than strings in Elixir?

Your best bet is to use Logger.info "Here is some thing: #{inspect thing}" . This way even if thing doesn't implement the String.Chars protocol, you still get something useful.

If the goal is to temporarily print something to the console instead of explicitly "logging" it, you can directly use IO.inspect/2 , instead of using inspect/2 in a Logger argument.

IO.inspect(params)

It pretty-prints by default and since it returns back the input, you can pipe it in an existing chain with a label, which is very helpful when debugging:

result =
  numbers
  |> IO.inspect(label: "Input list")
  |> Enum.filter(& rem(&1, 3) == 0)
  |> IO.inspect(label: "Filtered to multiples of 3")
  |> Enum.map(& &1 * &1)
  |> IO.inspect(label: "Numbers Squared")
  |> Enum.sum()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM