Home > Blockchain >  How to "inspect to file" (or to string) in Elixir?
How to "inspect to file" (or to string) in Elixir?

Time:04-29

In Elixir, we can IO.inspect anyStructure to get anyStructure's internals printed to output. Is there a similar method to output it to a file (or, as a more flexible solution, to a string)?

I've looked through some articles on debugging and io but don't see a solution. I've also tried

{:ok, file} = File.open("test.log", [:append, {:delayed_write, 100, 20}])
structure = %{ a: 1, b: 2 }
IO.binwrite(file, structure)
File.close file

but that results in "no function clause matching in IO.binwrite/2 [...] def binwrite(device, iodata) when is_list(iodata) or is_binary(iodata)". I've also googled some "elixir serialize" and "elixir object to string", but haven't found anything useful (like :erlang.term_to_binary which returns, well, binary). Is there a simple way to get the same result that IO.inspect prints, into a file or a string?

CodePudding user response:

There is already inspect/2 function, just go with it:

#> inspect({1,2,3})
"{1, 2, 3}"

#> h inspect/2
                         def inspect(term, opts \\ [])

  @spec inspect(
          Inspect.t(),
          keyword()
        ) :: String.t()

Inspects the given argument according to the Inspect protocol. The second
argument is a keyword list with options to control inspection.


You can do whatever you wish with the string afterwards.

CodePudding user response:

You can give IO.inspect an additional param to tell it where to write to:

{:ok, pid} = StringIO.open("")
IO.inspect(pid, %{test: "data"}, label: "IO.inspect options work too \o/")
{:ok, {_in, out}} = StringIO.close(pid)

out # "IO.inspect options work too o/: %{test: \"data\"}\n"

It accepts a pid of a process to write to. StringIO provides such a process, returning you a string on close.

  • Related