如何在Inno Setup中保留不超过一年的安装日志文件
Inno Setup 日志自动清理方案(仅保留一年内文件)
在你现有的CurStepChanged过程中,复制完日志后添加日志清理逻辑即可实现需求。核心思路是遍历目标日志文件夹,检查每个文件的时间戳,删除超过一年的旧日志。
修改后的完整代码
procedure CurStepChanged(CurStep: TSetupStep); var ResultCode: integer; strLogFilePathName, strLogFileName, strNewFilePathName: string; LogDir: string; FindRec: TFindRec; FileDateTime: TDateTime; OneYearAgo: TDateTime; begin if (CurStep = ssDone) then begin // 原日志复制逻辑 strLogFilePathName := ExpandConstant('{log}'); strLogFileName := ExtractFileName(strLogFilePathName); strNewFilePathName := ExpandConstant('{#CommonDataDir}\Installation Logs\') + strLogFileName; FileCopy(strLogFilePathName, strNewFilePathName, false); // 新增日志清理逻辑 LogDir := ExpandConstant('{#CommonDataDir}\Installation Logs\'); // 获取精确的一年前时间(自动处理闰年) OneYearAgo := Now - EncodeDate(1, 0, 0); // 遍历文件夹内所有.log文件 if FindFirst(LogDir + '*.log', FindRec) then begin try repeat // 跳过系统默认目录项 if (FindRec.Name <> '.') and (FindRec.Name <> '..') then begin // 获取文件修改时间(如需按创建时间判断,可改用FileAge函数) if GetFileDateTime(LogDir + FindRec.Name, FileDateTime) then begin // 若文件时间早于一年前则删除 if FileDateTime < OneYearAgo then begin DeleteFile(LogDir + FindRec.Name); end; end; end; until not FindNext(FindRec); finally FindClose(FindRec); end; end; end; end;
关键逻辑说明
- 时间计算:用
Now - EncodeDate(1, 0, 0)生成精确的一年前时间,自动适配闰年,比直接减365天更准确。 - 文件遍历:通过
FindFirst/FindNext遍历目标文件夹内的所有日志文件,跳过系统默认的.和..目录项。 - 时间判断:使用
GetFileDateTime获取文件修改时间,若需按创建时间筛选,可替换为FileAge函数转换时间戳。 - 安全清理:仅删除符合时间条件的旧日志,确保一年内的文件完整保留。
内容的提问来源于stack exchange,提问作者Andrew Truckle
相关产品推荐
相关产品推荐

