Files
Chronos/tests/Chronos.Core.Tests/Diagnostics/FileLogSinkTests.cs
T
Alby96 0e84392f4f feat(logs): log level, retention, size limits and rotation on server and desktop
Owner review 2, R11 asked for more log settings. The file sink now writes daily or
hourly files, continues a full file in numbered parts and prunes by age and by the
total size (never the file being written); its options change while it runs.

Server: the file and console levels are separate and read by the logging filters
at every line, so the admin panel's new Logs group applies without a restart; the
engine's level follows the lower of the two. This also fixes a bug: the file logger
was fixed at Information, so CHRONOS_LOG_LEVEL=Debug or Trace never reached the
files. New variables CHRONOS_LOG_CONSOLE_LEVEL, CHRONOS_LOG_RETENTION_DAYS,
CHRONOS_LOG_MAX_FILE_MB, CHRONOS_LOG_MAX_TOTAL_MB, CHRONOS_LOG_ROTATION,
CHRONOS_AUDIT_RETENTION_DAYS and CHRONOS_DIAGNOSTICS_LOG_MB lock their settings like
the others; the diagnostics zip keeps the configured share of each log.

Desktop: Settings > Advanced gains Log level, Keep logs, File size, Logs total,
Rotation and Diagnostics logs, applied at every save; Advanced's Reset section
restores them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit cc875784e4952ee0e4c807b9d9c18496d3d5a8c3)
2026-10-27 02:08:09 +01:00

168 lines
8.7 KiB
C#

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);
/// <summary>Names are fixed by this clock; far from today, so nothing is old enough to be pruned by age.</summary>
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));
sink.Write(LogLevel.Warning, "setup", "written", null);
var expected = Path.Combine(dir, $"setup-{DateTime.UtcNow:yyyyMMdd}.log");
Assert.Equal(expected, sink.CurrentPath);
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);
}
/// <summary>Reads a file the sink may still be writing (it shares it for reading and writing, as the log tail does).</summary>
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<string>().Order(StringComparer.Ordinal)];
}