You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 22:58:15