using Chronos.Core.Diagnostics; using Chronos.Testing; namespace Chronos.Core.Tests.Diagnostics; public sealed class FileLogSinkTests(TestContext context) { private static readonly string Block = new('x', 64 * 1024); /// Names are fixed by this clock; far from today, so nothing is old enough to be pruned by age. private sealed class ManualTime(DateTimeOffset now) : TimeProvider { public DateTimeOffset Now { get; set; } = now; public override DateTimeOffset GetUtcNow() => Now; } [Test] public void AFullFileContinuesInNumberedParts() { var dir = context.CreateTempDirectory(); var time = new ManualTime(new DateTimeOffset(2026, 10, 26, 9, 30, 0, TimeSpan.Zero)); using (var sink = new FileLogSink(dir, "p", new LogFileOptions { MaxFileMb = 1, MaxTotalMb = 0, RetentionDays = 0 }, time)) { // 40 blocks of 64 KiB: two full files of 1 MiB and the rest in a third. for (var i = 0; i < 40; i++) sink.Write(LogLevel.Info, "test", Block, null); Assert.Equal(Path.Combine(dir, "p-20261026.2.log"), sink.CurrentPath); } Assert.SequenceEqual(["p-20261026.1.log", "p-20261026.2.log", "p-20261026.log"], Names(dir)); var first = new FileInfo(Path.Combine(dir, "p-20261026.log")).Length; Assert.InRange(first, 1L << 20, (1L << 20) + Block.Length + 200); Assert.Greater(new FileInfo(Path.Combine(dir, "p-20261026.2.log")).Length, 0); } [Test] public void ARestartContinuesTheNewestPartUnlessItIsFull() { var dir = context.CreateTempDirectory(); File.WriteAllText(Path.Combine(dir, "p-20261026.log"), new string('a', 2 << 20)); File.WriteAllText(Path.Combine(dir, "p-20261026.1.log"), "earlier\n"); var time = new ManualTime(new DateTimeOffset(2026, 10, 26, 9, 30, 0, TimeSpan.Zero)); var options = new LogFileOptions { MaxFileMb = 1, MaxTotalMb = 0, RetentionDays = 0 }; using (var sink = new FileLogSink(dir, "p", options, time)) sink.Write(LogLevel.Info, "test", "after restart", null); var text = File.ReadAllText(Path.Combine(dir, "p-20261026.1.log")); Assert.True(text.StartsWith("earlier\n", StringComparison.Ordinal) && text.Contains("after restart", StringComparison.Ordinal), text); File.WriteAllText(Path.Combine(dir, "p-20261026.1.log"), new string('b', 1 << 20)); using (var sink = new FileLogSink(dir, "p", options, time)) sink.Write(LogLevel.Info, "test", "next part", null); Assert.Contains("next part", File.ReadAllText(Path.Combine(dir, "p-20261026.2.log"))); } [Test] public void HourlyFilesAreNamedByTheHourAndTheRotationChangesLive() { var dir = context.CreateTempDirectory(); var time = new ManualTime(new DateTimeOffset(2026, 10, 26, 13, 59, 59, TimeSpan.Zero)); using var sink = new FileLogSink(dir, "server", new LogFileOptions { Rotation = LogRotation.Hourly, RetentionDays = 0 }, time); sink.Write(LogLevel.Info, "test", "one", null); time.Now = time.Now.AddSeconds(2); sink.Write(LogLevel.Info, "test", "two", null); Assert.SequenceEqual(["server-20261026-13.log", "server-20261026-14.log"], Names(dir)); Assert.Contains("two", Read(Path.Combine(dir, "server-20261026-14.log"))); sink.Configure(sink.Options with { Rotation = LogRotation.Daily }); sink.Write(LogLevel.Info, "test", "three", null); Assert.Equal(Path.Combine(dir, "server-20261026.log"), sink.CurrentPath); Assert.Contains("three", Read(sink.CurrentPath)); } [Test] public void TheTotalSizeDropsTheOldestFilesButNeverTheCurrentOne() { var dir = context.CreateTempDirectory(); var now = DateTime.UtcNow; foreach (var (name, daysAgo) in new[] { ("p-20261020.log", 6), ("p-20261021.1.log", 5), ("p-20261022-08.log", 4) }) { var path = Path.Combine(dir, name); File.WriteAllText(path, new string('o', 600 * 1024)); File.SetLastWriteTimeUtc(path, now.AddDays(-daysAgo)); } // Other programs' files and names this sink never writes are left alone, whatever their size. File.WriteAllText(Path.Combine(dir, "other-20261019.log"), new string('o', 2 << 20)); File.WriteAllText(Path.Combine(dir, "p-notes.log"), new string('o', 2 << 20)); File.SetLastWriteTimeUtc(Path.Combine(dir, "p-notes.log"), now.AddDays(-30)); using var sink = new FileLogSink(dir, "p", new LogFileOptions { MaxTotalMb = 1, MaxFileMb = 0 }); sink.Write(LogLevel.Info, "test", "today", null); Assert.SequenceEqual(Sorted("other-20261019.log", "p-20261022-08.log", Path.GetFileName(sink.CurrentPath), "p-notes.log"), Names(dir)); // The file being written stays even when it alone is over the limit. for (var i = 0; i < 24; i++) sink.Write(LogLevel.Info, "test", Block, null); sink.PruneNow(); Assert.SequenceEqual(Sorted("other-20261019.log", Path.GetFileName(sink.CurrentPath), "p-notes.log"), Names(dir)); } [Test] public void FilesOlderThanTheRetentionAreDeleted() { var dir = context.CreateTempDirectory(); var now = DateTime.UtcNow; foreach (var (name, daysAgo) in new[] { ("p-20200101.log", 30), ("p-20200102.3.log", 20), ("p-20200103.log", 2), ("q-20200101.log", 30) }) { var path = Path.Combine(dir, name); File.WriteAllText(path, "old\n"); File.SetLastWriteTimeUtc(path, now.AddDays(-daysAgo)); } using var sink = new FileLogSink(dir, "p", new LogFileOptions { RetentionDays = 14 }); sink.Write(LogLevel.Info, "test", "today", null); Assert.SequenceEqual(Sorted("p-20200103.log", Path.GetFileName(sink.CurrentPath), "q-20200101.log"), Names(dir)); } [Test] public void ConfigureAppliesTheLevelAndTheRetentionAtOnce() { var dir = context.CreateTempDirectory(); using var sink = new FileLogSink(dir, "p", new LogFileOptions()); sink.Write(LogLevel.Debug, "test", "hidden", null); sink.Write(LogLevel.Info, "test", "shown", null); sink.Configure(sink.Options with { Level = LogLevel.Debug }); sink.Write(LogLevel.Debug, "test", "detail", null); sink.Configure(sink.Options with { Level = LogLevel.Error }); sink.Write(LogLevel.Warning, "test", "quiet", null); var text = Read(sink.CurrentPath); Assert.True(text.Contains("shown", StringComparison.Ordinal) && text.Contains("detail", StringComparison.Ordinal), text); Assert.False(text.Contains("hidden", StringComparison.Ordinal) || text.Contains("quiet", StringComparison.Ordinal), text); // A shorter retention prunes without waiting for the next file. var old = Path.Combine(dir, "p-20200101.log"); File.WriteAllText(old, "old\n"); File.SetLastWriteTimeUtc(old, DateTime.UtcNow.AddDays(-3)); sink.Configure(sink.Options with { RetentionDays = 7 }); Assert.FileExists(old); sink.Configure(sink.Options with { RetentionDays = 1 }); Assert.FileMissing(old); Assert.FileExists(sink.CurrentPath); } [Test] public void TheFormerConstructorWritesDailyFilesWithTheDefaultLimits() { var dir = context.CreateTempDirectory(); var sink = new FileLogSink(dir, "setup", 7); Assert.Equal(new LogFileOptions { RetentionDays = 7 }, sink.Options); Assert.Equal((LogLevel.Info, 50, 1024, LogRotation.Daily), (sink.Options.Level, sink.Options.MaxFileMb, sink.Options.MaxTotalMb, sink.Options.Rotation)); var before = DateTime.UtcNow; sink.Write(LogLevel.Warning, "setup", "written", null); var after = DateTime.UtcNow; // The system clock: a write across midnight UTC names either day. var expected = sink.CurrentPath; Assert.Contains(expected, new[] { before, after }.Select(day => Path.Combine(dir, $"setup-{day:yyyyMMdd}.log"))); sink.Dispose(); // Engine code may log after the host closed its sink: the line is dropped. sink.Write(LogLevel.Error, "setup", "after", null); var text = File.ReadAllText(expected); Assert.Contains("Warning setup: written", text); Assert.False(text.Contains("after", StringComparison.Ordinal), text); } /// Reads a file the sink may still be writing (it shares it for reading and writing, as the log tail does). private static string Read(string path) { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } private static string[] Sorted(params string[] names) => [.. names.Order(StringComparer.Ordinal)]; private static string[] Names(string dir) => [.. Directory.EnumerateFiles(dir).Select(Path.GetFileName).OfType().Order(StringComparer.Ordinal)]; }