1 -module(life_observer).
7 ,register_with_logger/0
23 -define(EVENT_MGR_REF, ?MODULE).
24 -define(HANDLER, ?MODULE).
26 -define(PATH_DIR__DATA, "data").
27 -define(CSV_DELIMITER, ",").
30 -record(state, {log_file :: file:io_device()}).
33 %% ============================================================================
35 %% ============================================================================
38 EventMgrName = {local, ?EVENT_MGR_REF},
39 {ok, PID} = gen_event:start_link(EventMgrName),
40 ok = add_handler(X, Y),
44 register_with_logger() ->
45 error_logger:add_report_handler(?HANDLER).
50 gen_event:add_handler(?EVENT_MGR_REF, ?HANDLER, Args).
55 gen_event:delete_handler(?EVENT_MGR_REF, ?HANDLER, Args).
58 log_generation(GenID, GenDuration, Dead, Alive) ->
59 Event = {generation, GenID, GenDuration, Dead, Alive},
60 gen_event:notify(?EVENT_MGR_REF, Event).
63 %% ============================================================================
65 %% ============================================================================
67 code_change(_Old, State, _Other) -> {ok, State}.
68 handle_call(_Request, State) -> Reply = ok, {ok, Reply, State}.
69 handle_info(_Info, State) -> {ok, State}.
72 %% ============================================================================
74 %% ============================================================================
78 {{Year, Month, Day}, {Hour, Min, Sec}} = calendar:local_time(),
79 DateTime = lists:flatten(io_lib:format(
80 "~4.10.0B-~2.10.0B-~2.10.0B--~2.10.0B:~2.10.0B:~2.10.0B",
81 [Year, Month, Day, Hour, Min, Sec]
84 FileNameComponents = [DateTime | [integer_to_list(I) || I <- [N, X, Y]]],
85 FileName = string:join(FileNameComponents, "--") ++ ".csv",
86 FilePath = filename:join(?PATH_DIR__DATA, FileName),
88 ok = validate_makedir(file:make_dir(?PATH_DIR__DATA)),
89 {ok, LogFile} = file:open(FilePath, write),
91 CSVHeaders = ["Generation", "Duration", "Dead", "Alive"],
92 ok = do_write(LogFile, list_to_csvline(CSVHeaders)),
94 {ok, #state{log_file=LogFile}}.
97 terminate(_Reason, #state{log_file=LogFile}=State) ->
102 handle_event({generation, GenID, GenDuration, Dead, Alive},
103 #state{log_file=LogFile}=State) ->
105 Values = [integer_to_list(GenID)
106 ,float_to_string(GenDuration)
107 ,integer_to_list(Dead)
108 ,integer_to_list(Alive)
110 ok = do_write(LogFile, list_to_csvline(Values)),
114 %% ============================================================================
116 %% ============================================================================
118 validate_makedir(ok) -> ok;
119 validate_makedir({error, eexist}) -> ok;
120 validate_makedir(Other) -> Other.
123 do_write(File, Line) ->
124 ok = io:format(File, "~s~n", [Line]).
127 list_to_csvline(List) ->
128 string:join(List, ?CSV_DELIMITER).
131 float_to_string(Float) ->
132 io_lib:format("~f", [Float]).