-
Notifications
You must be signed in to change notification settings - Fork 6
/
logging.erl
83 lines (74 loc) · 2.39 KB
/
logging.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
-module(logging).
-export([log/3, log/4, init/0, timestamp/0, loop/3]).
log(Level, What, Message) -> log(Level, What, Message, []).
log(Level, What, Message, FormatParams) ->
case whereis(log) of
undefined -> Pid = spawn(logging, init, []);
Pid -> ok
end,
Pid ! {log, Level, What, Message, FormatParams},
ok.
mklog(Name) ->
file:make_dir("logs"),
case file:open(["logs/",Name,".log"], [append]) of
{ok, Log} ->
file:write(Log, [10, lists:duplicate(25, $#), 10]),
file:write(Log, io_lib:format("~s Log opened.~n~n", [timestamp()])),
{ok, Log};
{error, Reason} ->
io:fwrite("Unable to open log file logs/~s.log: ~s~n", [Name, Reason]), error
end.
mkentry(Level, What, Message, FormatParams) ->
io_lib:format("[~s][~s][~s] ~s~n", [timestamp(), Level, What, io_lib:format(Message, FormatParams)]).
datestr({Date,_}) -> datestr(Date);
datestr({Yr,Mn,Dy}) -> io_lib:format("~b-~b-~b", [Yr,Mn,Dy]).
init() -> init([debug, debug2, recv]).
init(Muted) ->
LogDate = datestr(calendar:now_to_universal_time(os:timestamp())),
case mklog(["main-", LogDate]) of
{ok, Log} ->
register(log, self()),
loop(Log, LogDate, Muted);
error -> fail
end.
loop(RLog, RLogDate, Muted) ->
receive
{all, Level} ->
NL = lists:delete(Level, Muted),
io:fwrite("~p~n", [NL]),
loop(RLog, RLogDate, NL);
{rll, Level} ->
case lists:member(Level, Muted) of
true -> NL = Muted;
false -> NL = [Level | Muted]
end,
io:fwrite("~p~n", [NL]),
loop(RLog, RLogDate, NL);
{log, Level, What, Message, FormatParams} ->
case datestr(calendar:now_to_universal_time(os:timestamp())) of
RLogDate -> Log = RLog, LogDate = RLogDate;
DateStr ->
case mklog(["main-", DateStr]) of
{ok, Log} ->
file:close(RLog),
LogDate = DateStr;
error ->
Log = RLog,
LogDate = RLogDate
end
end,
case lists:member(Level, Muted) of
false ->
io:fwrite("[~ts][~ts] ~ts~n", [Level, What, io_lib:format(Message, FormatParams)])
;
true -> ok
end
,
case file:write(Log, mkentry(Level, What, Message, FormatParams)) of
ok -> logging:loop(Log, LogDate, Muted);
{error, Reason} -> io:fwrite("[error][LOGGING] ~ts~n", [Reason]), init(Muted)
end;
stop -> ok
end.
timestamp() -> format_time(calendar:now_to_local_time(now())).
format_time({{Y, M, D}, {H, Mi, S}}) -> io_lib:format("~b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b", [Y, M, D, H, Mi, S]).