From 3b46f8fba46179117612a39af8fdfd551ff3e48a Mon Sep 17 00:00:00 2001 From: anlicheng <244108715@qq.com> Date: Wed, 19 Feb 2025 10:27:08 +0800 Subject: [PATCH] fix logger --- apps/iot/src/iot_logger.erl | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/apps/iot/src/iot_logger.erl b/apps/iot/src/iot_logger.erl index 7ffbd6b..79b62dc 100644 --- a/apps/iot/src/iot_logger.erl +++ b/apps/iot/src/iot_logger.erl @@ -13,6 +13,7 @@ %% API -export([start_link/1, start_link/2, write/2]). +-export([archive_file/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). @@ -89,12 +90,7 @@ handle_cast({write, Data}, State = #state{file = {OldIoDevice, OldFilePath}, que true -> ok = file:close(OldIoDevice), %% 归档 - erlang:spawn(fun() -> - %% 压缩文件 - ok = erl_tar:create(OldFilePath ++ ".tar", [OldFilePath], [compressed]), - %% 删除原来的文件 - ok = file:delete(OldFilePath) - end), + erlang:spawn(fun() -> archive_file(OldFilePath) end), %% 开启新的文件 NewFilePath = make_file(FileName, NDate), @@ -189,4 +185,17 @@ maybe_new_file({Y, M, D}, {Y0, M0, D0}) -> % {Date, _} = calendar:gregorian_seconds_to_datetime(Seconds - Day * 86400), % FilePath = make_file(FileName, Date), % filelib:is_file(FilePath) andalso file:delete(FilePath) -% end, lists:seq(1, 10)). \ No newline at end of file +% end, lists:seq(1, 10)). + + +-spec archive_file(FilePath :: string()) -> ok. +archive_file(FilePath) when is_list(FilePath) -> + TarFile = FilePath ++ ".tar", + {ok, Tar} = erl_tar:open(TarFile, [write, compressed]), + BaseName = filename:basename(FilePath), + {ok, Data} = file:read_file(FilePath), + + ok = erl_tar:add(Tar, Data, BaseName, []), + ok = erl_tar:close(Tar), + %% 删除原来的文件 + ok = file:delete(FilePath). \ No newline at end of file