简体   繁体   English

用于列表、元组等的 elixir 记录器

[英]elixir Logger for lists, tuples, etc

I can use the elixir logger for inspecting strings我可以使用 elixir 记录器来检查字符串

 > 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?你如何在 Elixir 中记录除字符串之外的列表、元组和数据类型?

Your best bet is to use Logger.info "Here is some thing: #{inspect thing}" .最好的办法是使用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.这样即使thing没有实现String.Chars协议,你仍然会得到一些有用的东西。

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/2 ,而不是在Logger参数中使用inspect/2

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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