using System; using System.IO; using System.Linq; using XP.Common.Dump.Configs; using XP.Common.Logging.Interfaces; namespace XP.Common.Dump.Implementations { /// /// Dump 文件自动清理组件,按保留天数策略删除过期文件 /// Auto cleanup component for dump files, deletes expired files based on retention policy /// internal class DumpCleaner { private readonly DumpConfig _config; private readonly ILoggerService _logger; public DumpCleaner(DumpConfig config, ILoggerService logger) { _config = config ?? throw new ArgumentNullException(nameof(config)); _logger = logger?.ForModule() ?? throw new ArgumentNullException(nameof(logger)); } /// /// 执行清理操作:删除超过保留天数的 .dmp 文件 /// Execute cleanup: delete .dmp files older than retention days /// public void CleanExpiredFiles() { try { if (!Directory.Exists(_config.StoragePath)) { _logger.Debug("存储目录不存在,跳过清理:{Path} | Storage directory does not exist, skipping cleanup: {Path}", _config.StoragePath); return; } var dmpFiles = Directory.GetFiles(_config.StoragePath, "*.dmp"); var cutoffTime = DateTime.Now.AddDays(-_config.RetentionDays); var deletedCount = 0; foreach (var filePath in dmpFiles) { try { var creationTime = File.GetCreationTime(filePath); if (creationTime < cutoffTime) { var fileName = Path.GetFileName(filePath); File.Delete(filePath); deletedCount++; _logger.Info("已删除过期 Dump 文件:{FileName} | Deleted expired dump file: {FileName}", fileName); } } catch (Exception ex) { _logger.Error(ex, "删除 Dump 文件失败:{FilePath} | Failed to delete dump file: {FilePath}", filePath); } } _logger.Info("Dump 清理完成,共删除 {Count} 个文件 | Dump cleanup completed, {Count} files deleted", deletedCount); } catch (Exception ex) { _logger.Error(ex, "Dump 清理过程发生异常:{Message} | Dump cleanup error: {Message}", ex.Message); } } } }