simple file logger

This commit is contained in:
anlicheng 2024-10-15 10:51:06 +08:00
parent e69a49a866
commit aa1e5d5d01

View File

@ -19,14 +19,10 @@
-define(SERVER, ?MODULE). -define(SERVER, ?MODULE).
%%
-define(BUFFER_SIZE, 100).
-record(state, { -record(state, {
file_name :: string(), file_name :: string(),
date :: calendar:date(), date :: calendar:date(),
file, file
buffer = []
}). }).
%%%=================================================================== %%%===================================================================
@ -53,11 +49,9 @@ start_link(FileName) when is_list(FileName) ->
{stop, Reason :: term()} | ignore). {stop, Reason :: term()} | ignore).
init([FileName]) -> init([FileName]) ->
ensure_dir(), ensure_dir(),
FilePath = make_file(FileName), FilePath = make_file(FileName, erlang:date()),
{ok, File} = file:open(FilePath, [append, binary]), {ok, File} = file:open(FilePath, [append, binary]),
erlang:start_timer(5000, self(), flush_ticker),
{ok, #state{file = File, file_name = FileName, date = get_date()}}. {ok, #state{file = File, file_name = FileName, date = get_date()}}.
%% @private %% @private
@ -79,14 +73,23 @@ handle_call(_Request, _From, State = #state{}) ->
{noreply, NewState :: #state{}} | {noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} | {noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}). {stop, Reason :: term(), NewState :: #state{}}).
handle_cast({write, Data}, State = #state{buffer = Buffer}) -> handle_cast({write, Data}, State = #state{file = OldFile, file_name = FileName, date = Date}) ->
Line = <<(time_prefix())/binary, " ", (format(Data))/binary, $\n>>, Line = iolist_to_binary([time_prefix(), <<" ">>, format(Data), <<$\n>>]),
NBuffer = [Line|Buffer], NDate = erlang:date(),
case length(NBuffer) >= ?BUFFER_SIZE of case maybe_new_file(Date, NDate) of
true -> true ->
{noreply, flush(State#state{buffer = NBuffer})}; file:close(OldFile),
FilePath = make_file(FileName, NDate),
{ok, File} = file:open(FilePath, [append, binary]),
ok = file:write(File, Line),
%% ,
delete_old_files(FileName, 30),
{noreply, State#state{file = File, date = get_date()}};
false -> false ->
{noreply, State#state{buffer = NBuffer}} ok = file:write(OldFile, Line),
{noreply, State}
end. end.
%% @private %% @private
@ -95,9 +98,6 @@ handle_cast({write, Data}, State = #state{buffer = Buffer}) ->
{noreply, NewState :: #state{}} | {noreply, NewState :: #state{}} |
{noreply, NewState :: #state{}, timeout() | hibernate} | {noreply, NewState :: #state{}, timeout() | hibernate} |
{stop, Reason :: term(), NewState :: #state{}}). {stop, Reason :: term(), NewState :: #state{}}).
handle_info({timeout, _, flush_ticker}, State) ->
erlang:start_timer(5000, self(), flush_ticker),
{noreply, flush(State)};
handle_info(_Info, State = #state{}) -> handle_info(_Info, State = #state{}) ->
{noreply, State}. {noreply, State}.
@ -123,29 +123,6 @@ code_change(_OldVsn, State = #state{}, _Extra) ->
%%% Internal functions %%% Internal functions
%%%=================================================================== %%%===================================================================
-spec flush(State :: #state{}) -> NState :: #state{}.
flush(State = #state{buffer = []}) ->
State;
flush(State = #state{file = OldFile, file_name = FileName, date = Date, buffer = Buffer}) ->
Content = iolist_to_binary(lists:reverse(Buffer)),
case maybe_new_file(Date) of
true ->
file:close(OldFile),
FilePath = make_file(FileName),
{ok, File} = file:open(FilePath, [append, binary]),
ok = file:write(File, Content),
%% ,
delete_old_files(FileName, 30),
State#state{file = File, buffer = [], date = get_date()};
false ->
ok = file:write(OldFile, Content),
State#state{buffer = []}
end.
format(Data) when is_binary(Data) -> format(Data) when is_binary(Data) ->
iolist_to_binary(Data); iolist_to_binary(Data);
format(Items) when is_list(Items) -> format(Items) when is_list(Items) ->
@ -155,11 +132,7 @@ time_prefix() ->
{{Y, M, D}, {H, I, S}} = calendar:local_time(), {{Y, M, D}, {H, I, S}} = calendar:local_time(),
iolist_to_binary(io_lib:format("[~b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b]", [Y, M, D, H, I, S])). iolist_to_binary(io_lib:format("[~b-~2..0b-~2..0b ~2..0b:~2..0b:~2..0b]", [Y, M, D, H, I, S])).
-spec make_file(LogFile :: string()) -> string(). -spec make_file(LogFile :: string(), {Year :: integer(), Month :: integer(), Day :: integer()}) -> string().
make_file(LogFile) when is_list(LogFile) ->
Date = erlang:date(),
make_file(LogFile, Date).
make_file(LogFile, {Year, Month, Day}) when is_list(LogFile) -> make_file(LogFile, {Year, Month, Day}) when is_list(LogFile) ->
Suffix = io_lib:format("~b~2..0b~2..0b", [Year, Month, Day]), Suffix = io_lib:format("~b~2..0b~2..0b", [Year, Month, Day]),
RootDir = code:root_dir() ++ "/log/", RootDir = code:root_dir() ++ "/log/",
@ -171,7 +144,7 @@ ensure_dir() ->
true -> true ->
ok; ok;
false -> false ->
file:make_dir(RootDir) ok = file:make_dir(RootDir)
end. end.
%% %%
@ -181,9 +154,8 @@ get_date() ->
Date. Date.
%% %%
-spec maybe_new_file(Date :: calendar:date()) -> boolean(). -spec maybe_new_file(Date :: calendar:date(), Date0 :: calendar:date()) -> boolean().
maybe_new_file({Y, M, D}) -> maybe_new_file({Y, M, D}, {Y0, M0, D0}) ->
{{Y0, M0, D0}, _} = calendar:local_time(),
not (Y =:= Y0 andalso M =:= M0 andalso D =:= D0). not (Y =:= Y0 andalso M =:= M0 andalso D =:= D0).
-spec delete_old_files(FileName :: string(), Days :: integer()) -> no_return(). -spec delete_old_files(FileName :: string(), Days :: integer()) -> no_return().
@ -193,10 +165,5 @@ delete_old_files(FileName, Days) when is_list(FileName), is_integer(Days) ->
lists:foreach(fun(Day) -> lists:foreach(fun(Day) ->
{Date, _} = calendar:gregorian_seconds_to_datetime(Seconds - Day * 86400), {Date, _} = calendar:gregorian_seconds_to_datetime(Seconds - Day * 86400),
FilePath = make_file(FileName, Date), FilePath = make_file(FileName, Date),
case filelib:is_file(FilePath) of filelib:is_file(FilePath) andalso file:delete(FilePath)
true ->
file:delete(FilePath);
false ->
ok
end
end, lists:seq(1, 10)). end, lists:seq(1, 10)).