Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 813
YakovL Avatar asked Oct 23 '25 11:10

YakovL


2 Answers

There is already inspect/2 function (not the same as IO.inspect), 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.

like image 123
Mikhail Aksenov Avatar answered Oct 25 '25 16:10

Mikhail Aksenov


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.

like image 26
tessi Avatar answered Oct 25 '25 15:10

tessi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!