fix(logs): apply log settings from the first line and name the locking variable

The desktop opened its log files with the default limits and wrote its first
line, which prunes, before Settings › Advanced › Logs were applied. Every start,
and every launch that only hands its file to the running Chronos, deleted logs
older than 14 days and cut the folder to 1 GB whatever the user kept.
AppLogging.Open now builds the sink from the stored settings before that line;
the settings are read again once the launch owns the data folder.

A total below one file deleted each finished file as the next one opened. The
rule now lives in LogFileOptions.TotalBelowFile: the server keeps refusing it,
the desktop raises the total to the file size and its rows no longer offer the
combination.

The desktop log rows threw on negative sizes from an imported or hand-edited
file and showed raw values the files never got; they now show the applied ones.

Upgraded Unraid and compose installs keep CHRONOS_LOG_LEVEL=Information, which
locks both levels. The lock stays; the server now reports which variable fixes
each locked setting (LockedBy), so the panel's tooltip names it exactly and says
to remove it to change the value there. The releases README tells upgraders.

The former-constructor log test no longer fails across midnight UTC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 8ba7162bd5926d34c5ec4e40e2a2dad063ee19c3)
This commit is contained in:
Alby96 committed 2026-10-27 09:56:46 +01:00
1 parent 8d66be709c
commit ac121acf7c
53 files changed
+254 -92

No files matched your search

@@ -1,4 +1,5 @@
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
@@ -58,6 +59,18 @@ public sealed class LogSettingsTests
var odd = new AppSettings { LogLevel = (LogLevel)42, LogRetentionDays = 0, LogMaxFileMb = -3, LogMaxTotalMb = -1, LogRotation = (LogRotation)7, DiagnosticsLogMb = 0 };
Assert.Equal(new LogFileOptions { RetentionDays = 1, MaxFileMb = 0, MaxTotalMb = 0 }, AppLogging.Options(odd));
Assert.Equal(1L << 20, AppLogging.DiagnosticsTailBytes(odd));
var huge = new AppSettings { LogRetentionDays = 99_999, LogMaxFileMb = 99_999, LogMaxTotalMb = int.MaxValue, DiagnosticsLogMb = 5000 };
Assert.Equal(new LogFileOptions { RetentionDays = 3650, MaxFileMb = 10_240, MaxTotalMb = 1_048_576 }, AppLogging.Options(huge));
Assert.Equal(1024L << 20, AppLogging.DiagnosticsTailBytes(huge));
// A total below one file would delete each finished file as the next one opens: it is raised to the file (the
// server refuses it). Without a file limit any total holds.
Assert.True(LogFileOptions.TotalBelowFile(500, 256));
Assert.False(LogFileOptions.TotalBelowFile(256, 256) || LogFileOptions.TotalBelowFile(500, 0) || LogFileOptions.TotalBelowFile(0, 256));
var below = AppLogging.Options(new AppSettings { LogMaxFileMb = 500, LogMaxTotalMb = 256 });
Assert.Equal((500, 500), (below.MaxFileMb, below.MaxTotalMb));
var free = AppLogging.Options(new AppSettings { LogMaxFileMb = 0, LogMaxTotalMb = 256 });
Assert.Equal((0, 256), (free.MaxFileMb, free.MaxTotalMb));
var level = Log.MinimumLevel;
using var sink = new FileLogSink(_context.CreateTempDirectory(), "chronos");
@@ -73,6 +86,33 @@ public sealed class LogSettingsTests
}
}
[Test]
public void TheLogFilesStartWithTheSettings()
{
// App opens its files with the settings: the first line opens a file and prunes, at every start and at every launch
// that only hands over to the running Chronos, so the defaults would delete what the user keeps longer.
var level = Log.MinimumLevel;
try
{
foreach (var (settings, kept) in new[] { (new AppSettings { LogLevel = LogLevel.Debug, LogRetentionDays = 365, LogMaxTotalMb = 0 }, true), (new AppSettings(), false) })
{
var dir = _context.CreateTempDirectory();
var old = Path.Combine(dir, $"chronos-{DateTime.UtcNow.AddDays(-30):yyyyMMdd}.log");
File.WriteAllText(old, "a month ago");
File.SetLastWriteTimeUtc(old, DateTime.UtcNow.AddDays(-30));
using var sink = AppLogging.Open(dir, settings);
Assert.Equal((AppLogging.Options(settings), settings.LogLevel), (sink.Options, Log.MinimumLevel));
sink.Write(LogLevel.Info, "app", "Chronos starting", null);
Assert.Equal(kept, File.Exists(old), $"retention {settings.LogRetentionDays} days");
Assert.FileExists(sink.CurrentPath);
}
}
finally
{
Log.MinimumLevel = level;
}
}
[Test]
public void EachRowStoresAndSavesItsChoice()
{
@@ -100,7 +140,9 @@ public sealed class LogSettingsTests
Assert.Equal((LogLevel.Debug, 90, 0, 5120, LogRotation.Hourly, 16),
(settings.LogLevel, settings.LogRetentionDays, settings.LogMaxFileMb, settings.LogMaxTotalMb, settings.LogRotation, settings.DiagnosticsLogMb));
Assert.Equal(6, saves);
Assert.SequenceEqual(["SelectedLevel", "SelectedRetention", "SelectedFileSize", "SelectedTotalSize", "SelectedRotation", "SelectedDiagnostics"], changed);
// A size changes the choices of the other.
Assert.SequenceEqual(["SelectedLevel", "SelectedRetention", "SelectedFileSize", "TotalSizeChoices", "SelectedTotalSize", "SelectedTotalSize",
"FileSizeChoices", "SelectedFileSize", "SelectedRotation", "SelectedDiagnostics"], changed);
// The same choice again, or none (a list being rebuilt), changes nothing.
rows.SelectedLevel = rows.Levels.Single(l => l.Value == LogLevel.Debug);
@@ -122,4 +164,58 @@ public sealed class LogSettingsTests
Assert.Equal(string.Empty, changed.Single());
Assert.Equal(6, saves);
}
[Test]
public void TheSizeRowsNeverOfferATotalBelowOneFile()
{
var settings = new AppSettings { LogMaxFileMb = 500 };
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
Assert.SequenceEqual([512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
Assert.SequenceEqual([10, 20, 50, 100, 200, 500, 0], rows.FileSizeChoices.Select(c => c.Value));
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 512);
rows.SelectedFileSize = rows.FileSizeChoices.Single(c => c.Value == 100);
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 256);
Assert.Equal((100, 256, 3), (settings.LogMaxFileMb, settings.LogMaxTotalMb, saves));
Assert.SequenceEqual([10, 20, 50, 100, 200, 0], rows.FileSizeChoices.Select(c => c.Value));
// Without a file limit every total is offered, and without a total every file size.
rows.SelectedFileSize = rows.FileSizeChoices[^1];
Assert.SequenceEqual([256, 512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
rows.SelectedTotalSize = rows.TotalSizeChoices[^1];
Assert.SequenceEqual([10, 20, 50, 100, 200, 500, 0], rows.FileSizeChoices.Select(c => c.Value));
// An imported file with a total below its file size shows the total the files get.
settings.LogMaxFileMb = 500;
settings.LogMaxTotalMb = 256;
Assert.Equal(("500 MB", "500 MB"), (rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label));
Assert.SequenceEqual([500, 512, 1024, 2048, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
}
[Test]
public void OutOfRangeValuesShowWhatTheFilesGet()
{
// A hand-edited or imported settings file: every row shows the value applied, and none fails to find its choice.
var settings = new AppSettings { LogLevel = (LogLevel)42, LogRetentionDays = 0, LogMaxFileMb = -3, LogMaxTotalMb = -1, LogRotation = (LogRotation)7, DiagnosticsLogMb = 0 };
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
Assert.Equal(("Information", "1 day", "No limit", "No limit", "Daily", "1 MB"), (rows.SelectedLevel.Label, rows.SelectedRetention.Label,
rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedRotation.Label, rows.SelectedDiagnostics.Label));
Assert.SequenceEqual(LogSettingsRows.RetentionPresets, rows.RetentionChoices.Select(c => c.Value));
Assert.SequenceEqual([.. LogSettingsRows.FileSizePresets, 0], rows.FileSizeChoices.Select(c => c.Value));
Assert.SequenceEqual(LogSettingsRows.DiagnosticsPresets, rows.DiagnosticsChoices.Select(c => c.Value));
// Choosing the value shown saves it as applied.
var (shownFile, shownRetention) = (rows.SelectedFileSize, rows.SelectedRetention);
rows.SelectedFileSize = shownFile;
rows.SelectedRetention = shownRetention;
Assert.Equal((0, 1, 2), (settings.LogMaxFileMb, settings.LogRetentionDays, saves));
settings.LogRetentionDays = 99_999;
settings.LogMaxFileMb = 99_999;
settings.LogMaxTotalMb = int.MaxValue;
settings.DiagnosticsLogMb = 5000;
Assert.Equal(("3650 days", "10,240 MB", "1,048,576 MB", "1,024 MB"),
(rows.SelectedRetention.Label, rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedDiagnostics.Label));
}
}
@@ -142,9 +142,12 @@ public sealed class FileLogSinkTests(TestContext context)
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 expected = Path.Combine(dir, $"setup-{DateTime.UtcNow:yyyyMMdd}.log");
Assert.Equal(expected, sink.CurrentPath);
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);
@@ -147,19 +147,28 @@ public sealed partial class LoggingTests(TestContext context)
[Test]
public async Task LevelsSetByTheEnvironmentAreLocked()
{
await using var server = await TestServer.StartAsync(context, o => o.Locked = [nameof(ServerOptions.LogLevel), nameof(ServerOptions.ConsoleLogLevel)]);
// An install upgraded with the earlier compose file or Unraid template: CHRONOS_LOG_LEVEL fixes both levels.
await using var server = await TestServer.StartAsync(context, o =>
{
o.Locked = [nameof(ServerOptions.LogLevel), nameof(ServerOptions.ConsoleLogLevel), nameof(ServerOptions.LogRotation)];
o.LockedBy = new Dictionary<string, string> { [nameof(ServerOptions.LogLevel)] = "CHRONOS_LOG_LEVEL", [nameof(ServerOptions.ConsoleLogLevel)] = "CHRONOS_LOG_LEVEL" };
});
var admin = await server.AdminAsync();
var settings = await SettingsAsync(admin);
Assert.Contains("ConsoleLogLevel", settings.Locked);
// The panel's tooltip names the variable that fixes each; one locked without it is named by the variable that would.
string[] lockedBy = ["ConsoleLogLevel=CHRONOS_LOG_LEVEL", "LogLevel=CHRONOS_LOG_LEVEL", "LogRotation=CHRONOS_LOG_ROTATION"];
Assert.SequenceEqual(lockedBy, settings.LockedBy.Select(l => $"{l.Key}={l.Value}").Order(StringComparer.Ordinal));
var edited = settings with { HttpPort = 18080, HttpsPort = 18443 };
using (var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Logs = edited.Logs with { ConsoleLevel = "debug" } },
ProtocolJson.Default.ServerSettingsDto))
Assert.Equal("ConsoleLogLevel", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
Assert.Equal(LogLevel.Warning, server.Options.ConsoleLogLevel);
// The settings no variable fixes still save.
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Logs = edited.Logs with { RetentionDays = 7 } },
ProtocolJson.Default.ServerSettingsDto))
await saved.ExpectAsync(HttpStatusCode.OK);
// What a request says about the locks is ignored.
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings",
edited with { Logs = edited.Logs with { RetentionDays = 7 }, LockedBy = new Dictionary<string, string>() }, ProtocolJson.Default.ServerSettingsDto))
Assert.SequenceEqual(lockedBy, (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).LockedBy.Select(l => $"{l.Key}={l.Value}").Order(StringComparer.Ordinal));
Assert.Equal(7, server.Options.LogRetentionDays);
}
@@ -72,6 +72,8 @@ public sealed class StartupTests(TestContext context)
["CHRONOS_DISCOVERY"] = "false",
});
Assert.SequenceEqual(["Database", "HttpPort", "Discovery"], options.Locked);
// The admin panel names the variable that fixes each of them.
Assert.Equal(("CHRONOS_DB", "CHRONOS_HTTP_PORT", "CHRONOS_DISCOVERY"), (options.LockedBy["Database"], options.LockedBy["HttpPort"], options.LockedBy["Discovery"]));
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "many" }));
}
@@ -86,6 +88,7 @@ public sealed class StartupTests(TestContext context)
var former = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_WORKERS"] = "5" });
Assert.Equal((5, true), (former.Parallelism, former.FormerWorkersVariable));
Assert.SequenceEqual(["Database", "Parallelism"], former.Locked);
Assert.Equal("CHRONOS_WORKERS", former.LockedBy["Parallelism"]);
var both = ServerOptions.Load(new Dictionary<string, string?>
{
["CHRONOS_DATA_PATH"] = root,
@@ -96,6 +99,7 @@ public sealed class StartupTests(TestContext context)
});
Assert.Equal((7, true), (both.Parallelism, both.PriorityQueue));
Assert.SequenceEqual(["Database", "Parallelism", "PriorityQueue"], both.Locked);
Assert.Equal("CHRONOS_PARALLELISM", both.LockedBy["Parallelism"]);
Assert.False(ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PARALLELISM"] = "2" })
.FormerWorkersVariable);
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PRIORITY_QUEUE"] = "often" }));
@@ -174,6 +178,8 @@ public sealed class StartupTests(TestContext context)
var both = ServerOptions.Load(Env(("CHRONOS_LOG_LEVEL", "debug")));
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Debug, Microsoft.Extensions.Logging.LogLevel.Debug), (both.LogLevel, both.ConsoleLogLevel));
Assert.SequenceEqual(["Database", "LogLevel", "ConsoleLogLevel"], both.Locked);
// The earlier compose file and Unraid template set CHRONOS_LOG_LEVEL: the panel names it on both levels.
Assert.Equal(("CHRONOS_LOG_LEVEL", "CHRONOS_LOG_LEVEL"), (both.LockedBy["LogLevel"], both.LockedBy["ConsoleLogLevel"]));
var all = ServerOptions.Load(Env(("CHRONOS_LOG_LEVEL", "Trace"), ("CHRONOS_LOG_CONSOLE_LEVEL", "warn"), ("CHRONOS_LOG_RETENTION_DAYS", "30"),
("CHRONOS_LOG_MAX_FILE_MB", "0"), ("CHRONOS_LOG_MAX_TOTAL_MB", "2048"), ("CHRONOS_LOG_ROTATION", "Hourly"), ("CHRONOS_AUDIT_RETENTION_DAYS", "365"),
@@ -183,6 +189,7 @@ public sealed class StartupTests(TestContext context)
Assert.Equal((Chronos.Core.Diagnostics.LogRotation.Hourly, 365, 16), (all.LogRotation, all.AuditRetentionDays, all.DiagnosticsLogMb));
Assert.SequenceEqual(["Database", "LogLevel", "ConsoleLogLevel", "LogRetentionDays", "LogMaxFileMb", "LogMaxTotalMb", "LogRotation", "AuditRetentionDays",
"DiagnosticsLogMb"], all.Locked);
Assert.Equal(("CHRONOS_LOG_LEVEL", "CHRONOS_LOG_CONSOLE_LEVEL"), (all.LockedBy["LogLevel"], all.LockedBy["ConsoleLogLevel"]));
foreach (var invalid in new[]
{