Is there a way to redirect data printed by io:format()
from erlang shell into a file ? I know that I can open a file (IoDevice) and write data directly into it, but it requires code change and I don't want to do now.
views:
242answers:
5Just run it with erl -noinput -s module function -s init stop > file
.
Here's an example.
Erlang code:
-module(test).
-compile(export_all).
function() ->
io:fwrite("Hello world!~n").
In shell:
$ erlc test.erl
$ erl -noinput -s test function -s init stop > test.txt
$ cat test.txt
Hello world!
When a process calls io:format()
and similar functions, the process sends io request messages to its group_leader process. So a simple hack is to open a file, and set it as the group_leader of the processes producing the output. Here is an example of redirecting the shell process's output to a file.
1> {ok, F} = file:open("z", [write]).
{ok,<0.36.0>}
2> group_leader(F, self()).
3> io:format("Where am I going to appear?~n").
4>
This will only redirect the current shell process, so you will have to set the group_leader for all processes which you would like to redirect to the file.
The solution can be refined of course, for example by spawning a server process which proxies io request messages to rotated files, etc.
You can recompile your code with a parse transform, transforms calls like
io:format("~p~n", "Hello world!")
into calls like
io:format(whereis(my_output_file), "~p~n", "Hello world!")
Plus you need to add this into your start-up code, and you are done:
{ok, F} = file:open("file", [write]),
register(my_output_file, F),
I have a question that concern with this at How to know when user redirect output from erlang shell into a file.
Can you solve it!