清理历史log文件
This commit is contained in:
parent
55e7860ceb
commit
132c0aae90
@ -136,6 +136,18 @@ flush(State = #state{file = OldFile, file_name = FileName, date = Date, buffer =
|
|||||||
{ok, File} = file:open(FilePath, [append, binary]),
|
{ok, File} = file:open(FilePath, [append, binary]),
|
||||||
|
|
||||||
ok = file:write(File, Content),
|
ok = file:write(File, Content),
|
||||||
|
|
||||||
|
%% 清理历史的文件, 日志文件保留一个月的
|
||||||
|
OldFiles = list_old_files(FileName, 30),
|
||||||
|
[begin
|
||||||
|
case filelib:is_file(FilePath) of
|
||||||
|
true ->
|
||||||
|
file:delete(FilePath);
|
||||||
|
false ->
|
||||||
|
ok
|
||||||
|
end
|
||||||
|
end || FilePath <- OldFiles],
|
||||||
|
|
||||||
State#state{file = File, buffer = [], date = get_date()};
|
State#state{file = File, buffer = [], date = get_date()};
|
||||||
false ->
|
false ->
|
||||||
ok = file:write(OldFile, Content),
|
ok = file:write(OldFile, Content),
|
||||||
@ -153,7 +165,10 @@ time_prefix() ->
|
|||||||
|
|
||||||
-spec make_file(LogFile :: string()) -> string().
|
-spec make_file(LogFile :: string()) -> string().
|
||||||
make_file(LogFile) when is_list(LogFile) ->
|
make_file(LogFile) when is_list(LogFile) ->
|
||||||
{Year, Month, Day} = erlang:date(),
|
Date = erlang:date(),
|
||||||
|
make_file(LogFile, Date).
|
||||||
|
|
||||||
|
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/",
|
||||||
lists:flatten(RootDir ++ LogFile ++ "." ++ Suffix).
|
lists:flatten(RootDir ++ LogFile ++ "." ++ Suffix).
|
||||||
@ -177,4 +192,13 @@ get_date() ->
|
|||||||
-spec maybe_new_file(Date :: calendar:date()) -> boolean().
|
-spec maybe_new_file(Date :: calendar:date()) -> boolean().
|
||||||
maybe_new_file({Y, M, D}) ->
|
maybe_new_file({Y, M, D}) ->
|
||||||
{{Y0, M0, D0}, _} = calendar:local_time(),
|
{{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 list_old_files(LogFile :: string(), Days :: integer()) -> [string()].
|
||||||
|
list_old_files(LogFile, Days) when is_list(LogFile), is_integer(Days) ->
|
||||||
|
Seconds0 = calendar:datetime_to_gregorian_seconds(calendar:local_time()),
|
||||||
|
Seconds = Seconds0 - Days * 86400,
|
||||||
|
lists:map(fun(Day) ->
|
||||||
|
{Date, _} = calendar:gregorian_seconds_to_datetime(Seconds - Day * 86400),
|
||||||
|
make_file(LogFile, Date)
|
||||||
|
end, lists:seq(1, 10)).
|
||||||
Loading…
x
Reference in New Issue
Block a user