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)
This commit is contained in:
Alby96 committed 2026-10-27 02:08:09 +01:00
1 parent 1f089888e8
commit 0e84392f4f
35 files changed
+1485 -119

No files matched your search

@@ -0,0 +1,125 @@
using System.Globalization;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.App.Tests.Settings;
/// <summary>Settings › Advanced › Logs (owner review 2, R11): the stored values, the file options they become and the rows.</summary>
public sealed class LogSettingsTests
{
private readonly TestContext _context;
public LogSettingsTests(TestContext context)
{
_context = context;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
[Test]
public void LogSettingsSurviveTheSettingsFileAndOlderFilesGetTheDefaults()
{
var settings = new AppSettings
{
LogLevel = LogLevel.Debug,
LogRetentionDays = 30,
LogMaxFileMb = 0,
LogMaxTotalMb = 2048,
LogRotation = LogRotation.Hourly,
DiagnosticsLogMb = 16,
};
var json = settings.ToJson();
Assert.Contains("\"LogLevel\": \"Debug\"", json);
Assert.Contains("\"LogRotation\": \"Hourly\"", json);
foreach (var copy in new[] { AppSettings.Parse(json)!, settings.Clone() })
{
Assert.Equal((LogLevel.Debug, 30, 0, 2048, LogRotation.Hourly, 16),
(copy.LogLevel, copy.LogRetentionDays, copy.LogMaxFileMb, copy.LogMaxTotalMb, copy.LogRotation, copy.DiagnosticsLogMb));
}
// A settings file written before these rows existed (or exported by such a copy) keeps the former behaviour's defaults.
var older = AppSettings.Parse("""{ "Theme": "Light" }""")!;
Assert.Equal((LogLevel.Info, 14, 50, 1024, LogRotation.Daily, 4),
(older.LogLevel, older.LogRetentionDays, older.LogMaxFileMb, older.LogMaxTotalMb, older.LogRotation, older.DiagnosticsLogMb));
}
[Test]
public void TheSettingsBecomeTheLogFileOptions()
{
Assert.Equal(new LogFileOptions(), AppLogging.Options(new AppSettings()));
Assert.Equal(4L << 20, AppLogging.DiagnosticsTailBytes(new AppSettings()));
var tuned = new AppSettings { LogLevel = LogLevel.Warning, LogRetentionDays = 3, LogMaxFileMb = 10, LogMaxTotalMb = 0, LogRotation = LogRotation.Hourly };
Assert.Equal(new LogFileOptions { Level = LogLevel.Warning, RetentionDays = 3, MaxFileMb = 10, MaxTotalMb = 0, Rotation = LogRotation.Hourly },
AppLogging.Options(tuned));
// A hand-edited file never makes the sink keep nothing or delete everything.
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 level = Log.MinimumLevel;
using var sink = new FileLogSink(_context.CreateTempDirectory(), "chronos");
try
{
AppLogging.Apply(sink, tuned);
Assert.Equal(AppLogging.Options(tuned), sink.Options);
Assert.Equal(LogLevel.Warning, Log.MinimumLevel);
}
finally
{
Log.MinimumLevel = level;
}
}
[Test]
public void EachRowStoresAndSavesItsChoice()
{
var settings = new AppSettings();
var saves = 0;
var rows = new LogSettingsRows(settings, () => saves++);
var changed = new List<string?>();
rows.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
Assert.SequenceEqual(["Trace", "Debug", "Information", "Warning", "Error"], rows.Levels.Select(l => l.Label));
Assert.Equal(("Information", "14 days", "50 MB", "1,024 MB", "Daily", "4 MB"), (rows.SelectedLevel.Label, rows.SelectedRetention.Label,
rows.SelectedFileSize.Label, rows.SelectedTotalSize.Label, rows.SelectedRotation.Label, rows.SelectedDiagnostics.Label));
Assert.Equal("1 day", rows.RetentionChoices[0].Label);
// "No limit" closes both size lists.
Assert.Equal((0, "No limit"), (rows.FileSizeChoices[^1].Value, rows.FileSizeChoices[^1].Label));
Assert.Equal(0, rows.TotalSizeChoices[^1].Value);
Assert.SequenceEqual(["Daily", "Hourly"], rows.Rotations.Select(r => r.Label));
rows.SelectedLevel = rows.Levels.Single(l => l.Value == LogLevel.Debug);
rows.SelectedRetention = rows.RetentionChoices.Single(c => c.Value == 90);
rows.SelectedFileSize = rows.FileSizeChoices[^1];
rows.SelectedTotalSize = rows.TotalSizeChoices.Single(c => c.Value == 5120);
rows.SelectedRotation = rows.Rotations.Single(r => r.Value == LogRotation.Hourly);
rows.SelectedDiagnostics = rows.DiagnosticsChoices.Single(c => c.Value == 16);
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);
// The same choice again, or none (a list being rebuilt), changes nothing.
rows.SelectedLevel = rows.Levels.Single(l => l.Value == LogLevel.Debug);
rows.SelectedRotation = null!;
Assert.Equal(6, saves);
// Values set elsewhere are listed in order with the presets.
settings.LogRetentionDays = 45;
settings.LogMaxTotalMb = 3000;
Assert.SequenceEqual([1, 3, 7, 14, 30, 45, 90, 365], rows.RetentionChoices.Select(c => c.Value));
Assert.Equal("45 days", rows.SelectedRetention.Label);
Assert.SequenceEqual([256, 512, 1024, 2048, 3000, 5120, 10240, 0], rows.TotalSizeChoices.Select(c => c.Value));
// Reset section on Advanced: the defaults, shown at once; the caller saves.
changed.Clear();
rows.Reset();
Assert.Equal((LogLevel.Info, 14, 50, 1024, LogRotation.Daily, 4),
(settings.LogLevel, settings.LogRetentionDays, settings.LogMaxFileMb, settings.LogMaxTotalMb, settings.LogRotation, settings.DiagnosticsLogMb));
Assert.Equal(string.Empty, changed.Single());
Assert.Equal(6, saves);
}
}
@@ -80,10 +80,13 @@ public sealed class SettingsScreenSmokeTests
var data = Field(app, Loc.L("Settings.Advanced.DataFolder"));
Assert.Equal(FlowDirection.LeftToRight, data.FlowDirection);
Assert.Equal(settings.DataFolder, data.ToolTip);
// Advanced has nothing to reset: no Reset section there.
Assert.False(settings.CanResetSection);
Assert.False(settings.ResetSectionCommand.CanExecute(null));
Assert.False(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "no Reset section on Advanced");
// Advanced's Reset section puts its log rows back to their defaults (owner review 2, R11).
Assert.True(settings.CanResetSection);
Assert.True(app.FindAll<Button>().Any(b => b.Content as string == Loc.L("Settings.ResetSection") && b.IsVisible), "a Reset section on Advanced");
settings.Logs.SelectedRotation = settings.Logs.Rotations.Single(r => r.Value == Chronos.Core.Diagnostics.LogRotation.Hourly);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Hourly, shell.Services.Settings.LogRotation);
settings.ResetSectionCommand.Execute(null);
Assert.Equal(Chronos.Core.Diagnostics.LogRotation.Daily, shell.Services.Settings.LogRotation);
// Forgetting a trusted certificate asks first, as on the Server screen; a "no" keeps it and the session.
settings.Page = SettingsPage.Server;
@@ -0,0 +1,167 @@
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)];
}
@@ -62,6 +62,27 @@ public sealed class DiagnosticsTests(TestContext context)
Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "server_diagnostics", 10, null)).Items);
}
[Test]
public async Task TheBundleKeepsTheEndOfEachLogTheSettingsAskFor()
{
// Owner review 2, R11: Settings › Logs › Diagnostics logs, 1 MB here.
await using var server = await TestServer.StartAsync(context, o => o.DiagnosticsLogMb = 1);
var admin = await server.AdminAsync();
var log = new System.Text.StringBuilder();
for (var i = 0; i < 30_000; i++) log.Append("line ").Append(i).Append(' ').Append('x', 90).Append('\n');
await File.WriteAllTextAsync(Path.Combine(server.Options.LogPath, "server-20200101.log"), log.ToString());
using var response = await admin.GetAsync("/api/v1/server/diagnostics");
await response.ExpectAsync(HttpStatusCode.OK);
await using var body = await response.Content.ReadAsStreamAsync();
using var zip = new ZipArchive(body, ZipArchiveMode.Read);
var tail = Read(zip.GetEntry("logs/server-20200101.log")!);
Assert.True(tail.StartsWith("[first ", StringComparison.Ordinal), "a cut log says so");
Assert.Contains("line 29999 ", tail);
// 1 MiB of the file, less the cut first line, with the note and the system's line ends (CRLF on Windows).
Assert.InRange(tail.Length, (1 << 20) - 200, (1 << 20) * 1.02);
}
private static string Read(ZipArchiveEntry entry)
{
using var reader = new StreamReader(entry.Open());
@@ -0,0 +1,184 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Chronos.Core.Diagnostics;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Hosting;
using Chronos.Testing;
using CoreLog = Chronos.Core.Diagnostics.Log;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Chronos.Server.Tests.Hosting;
/// <summary>
/// The server's log settings (owner review 2, R11). Serial: the engine's <see cref="CoreLog"/> is one per process, its
/// sink the last server's started and its level the lower of that server's two.
/// </summary>
[Category("server")]
[Serial]
public sealed partial class LoggingTests(TestContext context)
{
[Test]
public async Task DebugLinesReachTheFilesWhenTheLevelAsksForThem()
{
// The files' logger stopped at Information whatever CHRONOS_LOG_LEVEL said.
var root = context.CreateTempDirectory("debug-variable");
var variable = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_LOG_LEVEL"] = "Debug" });
Assert.Equal((LogLevel.Debug, LogLevel.Debug), (variable.LogLevel, variable.ConsoleLogLevel));
// The console stays at Warning, so the test log stays readable: the files have their own level.
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = variable.LogLevel);
var marker = Guid.NewGuid().ToString("N");
var logger = server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Chronos.Server.Tests");
logger.LogDebug("debug {Marker}", marker);
logger.LogTrace("trace {Marker}", marker);
CoreLog.Debug("tests", "engine debug " + marker);
// ASP.NET Core's own lines stay at Warning and above.
server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Microsoft.AspNetCore.Routing").LogDebug("routing {Marker}", marker);
var text = Logs(server);
Assert.Contains("Debug Chronos.Server.Tests: debug " + marker, text);
Assert.Contains("Debug Chronos.tests: engine debug " + marker, text);
Assert.False(text.Contains("trace " + marker, StringComparison.Ordinal), "Trace is below Debug");
Assert.False(text.Contains("routing " + marker, StringComparison.Ordinal), "request lines stay out");
var logging = server.Services.GetRequiredService<ServerLogging>();
Assert.Equal((LogLevel.Debug, LogLevel.Warning, Chronos.Core.Diagnostics.LogLevel.Debug), (logging.FileLevel, logging.ConsoleLevel, CoreLog.MinimumLevel));
}
[Test]
public async Task TheFileLevelChangesWhileTheServerRuns()
{
await using var server = await TestServer.StartAsync(context, o => o.LogLevel = LogLevel.Debug);
var admin = await server.AdminAsync();
var logger = server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Chronos.Server.Tests");
var marker = Guid.NewGuid().ToString("N");
logger.LogDebug("before {Marker}", marker);
var settings = await SettingsAsync(admin);
Assert.Equal(("debug", "warning"), (settings.Logs.FileLevel, settings.Logs.ConsoleLevel));
// The test server listens on ports the system chose (0), which no request may set.
var edited = settings with { HttpPort = 18080, HttpsPort = 18443, Logs = settings.Logs with { FileLevel = "information" } };
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
Assert.Equal("information", (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs.FileLevel);
logger.LogDebug("after {Marker}", marker);
CoreLog.Debug("tests", "engine after " + marker);
logger.LogInformation("information {Marker}", marker);
var text = Logs(server);
Assert.Contains("before " + marker, text);
Assert.Contains("information " + marker, text);
Assert.False(text.Contains("after " + marker, StringComparison.Ordinal), "Debug stopped at once");
Assert.Equal((LogLevel.Information, Chronos.Core.Diagnostics.LogLevel.Info), (server.Options.LogLevel, CoreLog.MinimumLevel));
var file = JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!.AsObject();
Assert.Equal("Information", file["LogLevel"]!.GetValue<string>());
Assert.False(file.ContainsKey("ConsoleLogLevel"), "only what changed is written");
}
[Test]
public async Task LogSettingsAreSavedAppliedAndValidated()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
var settings = await SettingsAsync(admin);
Assert.Equal(new LogSettingsDto("warning", "warning", 14, 50, 1024, "daily", 0, 4), settings.Logs);
var edited = settings with { HttpPort = 18080, HttpsPort = 18443, Logs = new LogSettingsDto("Debug", "error", 30, 10, 200, "Hourly", 365, 8) };
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", edited, ProtocolJson.Default.ServerSettingsDto))
Assert.Equal(new LogSettingsDto("debug", "error", 30, 10, 200, "hourly", 365, 8), (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs);
var o = server.Options;
Assert.Equal((LogLevel.Debug, LogLevel.Error, 30, 10, 200), (o.LogLevel, o.ConsoleLogLevel, o.LogRetentionDays, o.LogMaxFileMb, o.LogMaxTotalMb));
Assert.Equal((LogRotation.Hourly, 365, 8), (o.LogRotation, o.AuditRetentionDays, o.DiagnosticsLogMb));
var logging = server.Services.GetRequiredService<ServerLogging>();
Assert.Equal(new LogFileOptions { Level = Chronos.Core.Diagnostics.LogLevel.Debug, RetentionDays = 30, MaxFileMb = 10, MaxTotalMb = 200, Rotation = LogRotation.Hourly },
logging.Sink.Options);
Assert.Equal((LogLevel.Debug, LogLevel.Error), (logging.FileLevel, logging.ConsoleLevel));
// Without a restart, the next line goes to an hourly file.
var marker = Guid.NewGuid().ToString("N");
server.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Chronos.Server.Tests").LogWarning("hourly {Marker}", marker);
Assert.True(Directory.EnumerateFiles(o.LogPath).Any(f => HourlyName().IsMatch(Path.GetFileName(f)) && Read(f).Contains(marker, StringComparison.Ordinal)),
"an hourly file holds the line");
// server.json takes the names it reads back at the next start.
var file = JsonNode.Parse(await File.ReadAllTextAsync(o.SettingsFile))!.AsObject();
Assert.Equal(("Debug", "Error", "Hourly", 30, 365), (file["LogLevel"]!.GetValue<string>(), file["ConsoleLogLevel"]!.GetValue<string>(),
file["LogRotation"]!.GetValue<string>(), file["LogRetentionDays"]!.GetValue<int>(), file["AuditRetentionDays"]!.GetValue<int>()));
var restarted = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = o.DataPath, ["CHRONOS_DB"] = "postgres" });
Assert.Equal((LogLevel.Debug, LogLevel.Error, LogRotation.Hourly, 10, 200, 8), (restarted.LogLevel, restarted.ConsoleLogLevel, restarted.LogRotation,
restarted.LogMaxFileMb, restarted.LogMaxTotalMb, restarted.DiagnosticsLogMb));
// A panel that knows no log group keeps them as they are.
var older = JsonSerializer.SerializeToNode(edited with { ServerName = "Older panel" }, ProtocolJson.Default.ServerSettingsDto)!.AsObject();
Assert.True(older.Remove("logs"));
using (var content = new StringContent(older.ToJsonString(), Encoding.UTF8, "application/json"))
using (var saved = await admin.PutAsync("/api/v1/server/settings", content))
Assert.Equal(new LogSettingsDto("debug", "error", 30, 10, 200, "hourly", 365, 8), (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).Logs);
var logs = edited.Logs;
foreach (var (invalid, setting) in new (LogSettingsDto, string)[]
{
(logs with { FileLevel = "verbose" }, "LogLevel"),
(logs with { ConsoleLevel = "3" }, "ConsoleLogLevel"),
(logs with { Rotation = "weekly" }, "LogRotation"),
(logs with { RetentionDays = 0 }, "LogRetentionDays"),
(logs with { MaxFileMb = -1 }, "LogMaxFileMb"),
(logs with { MaxFileMb = 300 }, "LogMaxTotalMb"),
(logs with { MaxTotalMb = -5 }, "LogMaxTotalMb"),
(logs with { AuditRetentionDays = -1 }, "AuditRetentionDays"),
(logs with { DiagnosticsLogMb = 0 }, "DiagnosticsLogMb"),
})
{
using var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Logs = invalid }, ProtocolJson.Default.ServerSettingsDto);
Assert.Equal(setting, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
}
// No limits at all are a choice too.
using (var unlimited = await admin.PutAsJsonAsync("/api/v1/server/settings", edited with { Logs = logs with { MaxFileMb = 0, MaxTotalMb = 0 } },
ProtocolJson.Default.ServerSettingsDto))
await unlimited.ExpectAsync(HttpStatusCode.OK);
Assert.Equal((0, 0), (logging.Sink.Options.MaxFileMb, logging.Sink.Options.MaxTotalMb));
}
[Test]
public async Task LevelsSetByTheEnvironmentAreLocked()
{
await using var server = await TestServer.StartAsync(context, o => o.Locked = [nameof(ServerOptions.LogLevel), nameof(ServerOptions.ConsoleLogLevel)]);
var admin = await server.AdminAsync();
var settings = await SettingsAsync(admin);
Assert.Contains("ConsoleLogLevel", settings.Locked);
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);
Assert.Equal(7, server.Options.LogRetentionDays);
}
private static async Task<ServerSettingsDto> SettingsAsync(HttpClient admin)
{
using var read = await admin.GetAsync("/api/v1/server/settings");
return await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
}
/// <summary>Every server log file, read beside the sink that may still be writing it.</summary>
private static string Logs(TestServer server) => string.Concat(Directory.EnumerateFiles(server.Options.LogPath, "server-*.log").Order(StringComparer.Ordinal).Select(Read));
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();
}
[GeneratedRegex(@"^server-\d{8}-\d{2}(\.\d+)?\.log$")]
private static partial Regex HourlyName();
}
@@ -154,6 +154,45 @@ public sealed class StartupTests(TestContext context)
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres", ["CHRONOS_PUBLIC_HTTPS_PORT"] = invalid }));
}
[Test]
public void TheLogVariablesSetTheirSettingsAndLockThem()
{
// Owner review 2, R11: CHRONOS_LOG_LEVEL sets the files and the console, CHRONOS_LOG_CONSOLE_LEVEL the console alone.
var root = context.CreateTempDirectory("log-variables");
Dictionary<string, string?> Env(params (string Name, string Value)[] variables)
{
var env = new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = root, ["CHRONOS_DB"] = "postgres" };
foreach (var (name, value) in variables) env[name] = value;
return env;
}
var defaults = ServerOptions.Load(Env());
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Information, Microsoft.Extensions.Logging.LogLevel.Information, 14, 50, 1024),
(defaults.LogLevel, defaults.ConsoleLogLevel, defaults.LogRetentionDays, defaults.LogMaxFileMb, defaults.LogMaxTotalMb));
Assert.Equal((Chronos.Core.Diagnostics.LogRotation.Daily, 0, 4), (defaults.LogRotation, defaults.AuditRetentionDays, defaults.DiagnosticsLogMb));
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);
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"),
("CHRONOS_DIAGNOSTICS_LOG_MB", "16")));
Assert.Equal((Microsoft.Extensions.Logging.LogLevel.Trace, Microsoft.Extensions.Logging.LogLevel.Warning, 30, 0, 2048),
(all.LogLevel, all.ConsoleLogLevel, all.LogRetentionDays, all.LogMaxFileMb, all.LogMaxTotalMb));
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);
foreach (var invalid in new[]
{
("CHRONOS_LOG_LEVEL", "verbose"), ("CHRONOS_LOG_LEVEL", "2"), ("CHRONOS_LOG_CONSOLE_LEVEL", "loud"), ("CHRONOS_LOG_ROTATION", "weekly"),
("CHRONOS_LOG_RETENTION_DAYS", "0"), ("CHRONOS_LOG_MAX_FILE_MB", "-1"), ("CHRONOS_LOG_MAX_TOTAL_MB", "10"), ("CHRONOS_AUDIT_RETENTION_DAYS", "-1"),
("CHRONOS_DIAGNOSTICS_LOG_MB", "0"),
})
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(Env(invalid)), invalid.Item1 + "=" + invalid.Item2);
}
[Test]
public void HelpListsEveryVariable()
{
+1
View File
@@ -68,6 +68,7 @@ public sealed class TestServer : IAsyncDisposable
LoginAttemptsPerMinute = 1000,
// Info lines of the ~55 servers the suite starts would bury failures in the CI log.
LogLevel = Microsoft.Extensions.Logging.LogLevel.Warning,
ConsoleLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning,
};
Directory.CreateDirectory(options.ArchivePath);
configure?.Invoke(options);