Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ public static void Initialize(string logDirectory, string version = "Unknown", b
}

LogFile = Path.Combine(logDirectory, $"{DateTime.Now:yyyy-MM-dd-HHmmss}.log");


PruneExpiredLogs(logDirectory);

// Write session header to log file
WriteToFile("=== BootstrapMate Session Started ===");
WriteToFile($"Version: {version}");
Expand All @@ -68,6 +70,52 @@ public static void Initialize(string logDirectory, string version = "Unknown", b
}
}

/// <summary>
/// Deletes logs in <paramref name="logDirectory"/> older than the retention
/// window. Every run writes a new timestamped file and nothing has ever removed
/// one, so on a machine that has been enrolled for a year the directory holds
/// hundreds of them.
/// </summary>
/// <remarks>
/// Age comes from the file's last write time rather than its name: the directory
/// also collects logs written by wrapper scripts, which do not follow the
/// timestamped naming, and those need expiring too.
/// </remarks>
internal static void PruneExpiredLogs(string logDirectory, int? retentionDays = null)
{
var days = retentionDays ?? BootstrapMate.Core.BootstrapMateConstants.LogRetentionDays;
if (days <= 0)
{
return;
}

try
{
var cutoff = DateTime.Now.AddDays(-days);

foreach (var file in Directory.GetFiles(logDirectory, "*.log"))
{
try
{
var info = new FileInfo(file);
if (info.LastWriteTime < cutoff)
{
info.Delete();
}
}
catch
{
// A log still held open elsewhere throws here. Skip it and try
// again next run rather than aborting the sweep.
}
}
}
catch
{
// Retention is best-effort and must never stop a bootstrap run.
}
}

public static void Debug(string message)
{
Log(LogLevel.Debug, message);
Expand Down
6 changes: 6 additions & 0 deletions src/BootstrapMate.Core/BootstrapMateConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ public static class BootstrapMateConstants
/// <summary>Log file directory.</summary>
public const string LogDirectory = @"C:\ProgramData\ManagedBootstrap\logs";

/// <summary>
/// How long session logs are kept. Every run writes a new timestamped file, so
/// without a window the directory grows for the life of the machine.
/// </summary>
public const int LogRetentionDays = 30;

/// <summary>Cache directory for downloaded packages.</summary>
public const string CacheDirectory = @"C:\ProgramData\ManagedBootstrap\cache";

Expand Down
Loading