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

+158
View File
@@ -0,0 +1,158 @@
using Microsoft.Extensions.Logging.Console;
using Chronos.Core.Diagnostics;
using Chronos.Server.Configuration;
using CoreLogLevel = Chronos.Core.Diagnostics.LogLevel;
using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Chronos.Server.Hosting;
/// <summary>
/// The server's logging (BRIEF §14.1; owner review 2, R11): the console and the files of <c>/data/logs</c>, each with its
/// own level, which the logging filters read at every line so a change in the admin panel applies at once; the file
/// sink's retention, size limits and rotation; and the engine's <see cref="Log.MinimumLevel"/>, the lower of the two
/// levels, so engine lines reach whichever output wants them. ASP.NET Core's own categories never write below Warning and
/// the host's lifetime never below Information, whatever the levels.
/// </summary>
public sealed class ServerLogging
{
public const int MaxRetentionDays = 3650;
public const int MaxFileMb = 10 * 1024;
public const int MaxTotalMb = 1024 * 1024;
public const int MaxAuditRetentionDays = 36500;
public const int MaxDiagnosticsLogMb = 1024;
/// <summary>The ranges <see cref="Problem"/> checks, for the start-up error.</summary>
public const string Ranges = "log retention 1 to 3650 days, log file 0 to 10240 MB, logs total 0 to 1048576 MB and not below the log file, "
+ "audit retention 0 to 36500 days, diagnostics logs 1 to 1024 MB";
/// <summary>The levels the settings accept, least severe first; their wire names are lower case (<c>information</c>).</summary>
public static IReadOnlyList<MsLogLevel> Levels { get; } =
[MsLogLevel.Trace, MsLogLevel.Debug, MsLogLevel.Information, MsLogLevel.Warning, MsLogLevel.Error, MsLogLevel.Critical, MsLogLevel.None];
private volatile MsLogLevel _file;
private volatile MsLogLevel _console;
/// <summary>Opens the log files of <paramref name="options"/> and applies its levels (call once the data folder is prepared).</summary>
public ServerLogging(ServerOptions options)
{
Sink = new FileLogSink(options.LogPath, "server", FileOptions(options));
Apply(options);
}
public FileLogSink Sink { get; }
public MsLogLevel FileLevel => _file;
public MsLogLevel ConsoleLevel => _console;
/// <summary>The console and the file provider, each behind a filter that reads its level now.</summary>
public void AddTo(ILoggingBuilder logging)
{
logging.ClearProviders();
// Every level reaches the filters; they decide with the levels of the moment.
logging.SetMinimumLevel(MsLogLevel.Trace);
logging.AddSimpleConsole(c => c.SingleLine = true);
logging.AddProvider(new FileLoggerProvider(this));
logging.AddFilter<ConsoleLoggerProvider>((category, level) => Allows(category, level, ConsoleLevel));
logging.AddFilter<FileLoggerProvider>((category, level) => Allows(category, level, FileLevel));
}
/// <summary>The levels, retention, limits and rotation of <paramref name="options"/>, from the next line on.</summary>
public void Apply(ServerOptions options)
{
_file = options.LogLevel;
_console = options.ConsoleLogLevel;
Sink.Configure(FileOptions(options));
Log.MinimumLevel = Core(options.LogLevel < options.ConsoleLogLevel ? options.LogLevel : options.ConsoleLogLevel);
}
public static LogFileOptions FileOptions(ServerOptions options) => new()
{
Level = Core(options.LogLevel),
RetentionDays = options.LogRetentionDays,
MaxFileMb = options.LogMaxFileMb,
MaxTotalMb = options.LogMaxTotalMb,
Rotation = options.LogRotation,
};
/// <summary>Whether a line of <paramref name="category"/> at <paramref name="level"/> is written by an output at <paramref name="threshold"/>.</summary>
public static bool Allows(string? category, MsLogLevel level, MsLogLevel threshold)
{
if (level == MsLogLevel.None || level < threshold) return false;
if (category is null) return true;
// A line per request below Warning would bury everything else.
if (category.StartsWith("Microsoft.AspNetCore", StringComparison.OrdinalIgnoreCase)) return level >= MsLogLevel.Warning;
if (category.StartsWith("Microsoft.Hosting.Lifetime", StringComparison.OrdinalIgnoreCase)) return level >= MsLogLevel.Information;
return true;
}
/// <summary>The engine's level of an ASP.NET Core level (Critical and None become Error, the engine's most severe).</summary>
public static CoreLogLevel Core(MsLogLevel level) => level switch
{
MsLogLevel.Trace => CoreLogLevel.Trace,
MsLogLevel.Debug => CoreLogLevel.Debug,
MsLogLevel.Information => CoreLogLevel.Info,
MsLogLevel.Warning => CoreLogLevel.Warning,
_ => CoreLogLevel.Error,
};
public static bool IsLevel(MsLogLevel level) => Levels.Contains(level);
/// <summary><c>information</c>.</summary>
public static string Wire(MsLogLevel level) => level.ToString().ToLowerInvariant();
/// <summary><c>daily</c> or <c>hourly</c>.</summary>
public static string Wire(LogRotation rotation) => rotation.ToString().ToLowerInvariant();
/// <summary>A level by name, any case; <c>info</c>, <c>warn</c> and <c>off</c> are accepted too. Numbers are not levels.</summary>
public static bool TryParseLevel(string? text, out MsLogLevel level)
{
level = MsLogLevel.Information;
var name = text?.Trim();
if (string.IsNullOrEmpty(name)) return false;
if (name.Equals("info", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.Information);
else if (name.Equals("warn", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.Warning);
else if (name.Equals("off", StringComparison.OrdinalIgnoreCase)) name = nameof(MsLogLevel.None);
foreach (var candidate in Levels)
{
if (!candidate.ToString().Equals(name, StringComparison.OrdinalIgnoreCase)) continue;
level = candidate;
return true;
}
return false;
}
public static bool TryParseRotation(string? text, out LogRotation rotation)
{
rotation = LogRotation.Daily;
foreach (var candidate in Enum.GetValues<LogRotation>())
{
if (!candidate.ToString().Equals(text?.Trim(), StringComparison.OrdinalIgnoreCase)) continue;
rotation = candidate;
return true;
}
return false;
}
/// <exception cref="FormatException">Not a level.</exception>
public static MsLogLevel ParseLevel(string variable, string value) => TryParseLevel(value, out var level)
? level
: throw new FormatException($"{variable} must be Trace, Debug, Information, Warning, Error, Critical or None.");
/// <exception cref="FormatException">Neither daily nor hourly.</exception>
public static LogRotation ParseRotation(string variable, string value) => TryParseRotation(value, out var rotation)
? rotation
: throw new FormatException($"{variable} must be daily or hourly.");
/// <summary>The setting (a <see cref="ServerOptions"/> property name) whose value is out of range, or null.</summary>
public static string? Problem(int retentionDays, int maxFileMb, int maxTotalMb, int auditRetentionDays, int diagnosticsLogMb)
{
if (retentionDays is < 1 or > MaxRetentionDays) return nameof(ServerOptions.LogRetentionDays);
if (maxFileMb is < 0 or > MaxFileMb) return nameof(ServerOptions.LogMaxFileMb);
// A total below one file would delete every finished file at once.
if (maxTotalMb is < 0 or > MaxTotalMb || (maxTotalMb > 0 && maxFileMb > maxTotalMb)) return nameof(ServerOptions.LogMaxTotalMb);
if (auditRetentionDays is < 0 or > MaxAuditRetentionDays) return nameof(ServerOptions.AuditRetentionDays);
if (diagnosticsLogMb is < 1 or > MaxDiagnosticsLogMb) return nameof(ServerOptions.DiagnosticsLogMb);
return null;
}
}