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

+3 -1
View File
@@ -41,7 +41,9 @@ public partial class App : Application
var capture = captureIndex >= 0;
// Capture never reads or writes the user's data folder.
Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect();
_log = new FileLogSink(Environment.LogDirectory, "chronos");
// Settings › Advanced › Logs from the first line, which prunes the folder: also a launch that only hands over. The
// settings are read again once this launch owns the data folder, since a Chronos that was closing saves them on exit.
_log = AppLogging.Open(Environment.LogDirectory, capture ? new AppSettings() : AppSettings.Load(Environment.SettingsPath));
// Capture runs in CI: mirror the log to stderr so failures are visible in the job output.
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
Log.Info("app", $"Chronos {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
+25 -8
View File
@@ -5,7 +5,8 @@ namespace Chronos.App.Infrastructure;
/// <summary>
/// Settings › Advanced › Logs applied to this PC's log files (owner review 2, R11): the level, retention, size limits and
/// rotation of the <see cref="FileLogSink"/> App starts with, and the engine's <see cref="Log.MinimumLevel"/> (the files
/// are the only output outside screenshots). Values outside the ranges Settings offers are brought within them.
/// are the only output outside screenshots). Values outside the ranges Settings offers are brought within them, and a
/// total below one file is raised to that file (<see cref="LogFileOptions.TotalBelowFile"/>), which the server refuses.
/// </summary>
public static class AppLogging
{
@@ -16,18 +17,34 @@ public static class AppLogging
public const int MaxTotalMb = 1024 * 1024;
public const int MaxDiagnosticsLogMb = 1024;
public static LogFileOptions Options(AppSettings settings) => new()
public static LogFileOptions Options(AppSettings settings)
{
Level = Enum.IsDefined(settings.LogLevel) ? settings.LogLevel : LogLevel.Info,
RetentionDays = int.Clamp(settings.LogRetentionDays, 1, MaxRetentionDays),
MaxFileMb = int.Clamp(settings.LogMaxFileMb, 0, MaxFileMb),
MaxTotalMb = int.Clamp(settings.LogMaxTotalMb, 0, MaxTotalMb),
Rotation = Enum.IsDefined(settings.LogRotation) ? settings.LogRotation : LogRotation.Daily,
};
var file = int.Clamp(settings.LogMaxFileMb, 0, MaxFileMb);
var total = int.Clamp(settings.LogMaxTotalMb, 0, MaxTotalMb);
return new()
{
Level = Enum.IsDefined(settings.LogLevel) ? settings.LogLevel : LogLevel.Info,
RetentionDays = int.Clamp(settings.LogRetentionDays, 1, MaxRetentionDays),
MaxFileMb = file,
MaxTotalMb = LogFileOptions.TotalBelowFile(file, total) ? file : total,
Rotation = Enum.IsDefined(settings.LogRotation) ? settings.LogRotation : LogRotation.Daily,
};
}
/// <summary>Bytes the diagnostics bundle keeps from the end of each log file.</summary>
public static long DiagnosticsTailBytes(AppSettings settings) => int.Clamp(settings.DiagnosticsLogMb, 1, MaxDiagnosticsLogMb) * LogFileOptions.BytesPerMb;
/// <summary>
/// The log files App starts with, in <paramref name="directory"/>, with <paramref name="settings"/> from the first line:
/// that line opens a file and prunes, so the defaults would delete what the user keeps longer.
/// </summary>
public static FileLogSink Open(string directory, AppSettings settings)
{
var options = Options(settings);
Log.MinimumLevel = options.Level;
return new FileLogSink(directory, "chronos", options);
}
/// <summary>The settings to <paramref name="sink"/> and the engine, from the next line on.</summary>
public static void Apply(FileLogSink sink, AppSettings settings)
{
+61 -17
View File
@@ -8,8 +8,10 @@ namespace Chronos.App.Settings;
/// <summary>
/// The log rows of Settings › Advanced (owner review 2, R11): level, retention, file size, total size and rotation of this
/// PC's log files, and how much of each the diagnostics bundle keeps. Each choice is stored and saved at once, and saving
/// applies it to the files (<see cref="AppLogging"/>). A value set elsewhere (an imported settings file) is listed with
/// the presets, never shown as another one.
/// applies it to the files (<see cref="AppLogging"/>). The rows show the values the files get: one set elsewhere (an
/// imported or hand-edited settings file) is brought within range as <see cref="AppLogging.Options"/> does, then listed
/// with the presets. File sizes above the total and totals below the file size are not offered
/// (<see cref="LogFileOptions.TotalBelowFile"/>).
/// </summary>
public sealed class LogSettingsRows(AppSettings settings, Action save) : ObservableObject
{
@@ -28,28 +30,49 @@ public sealed class LogSettingsRows(AppSettings settings, Action save) : Observa
}
public IReadOnlyList<SettingsOption<int>> RetentionChoices =>
[.. With(RetentionPresets, settings.LogRetentionDays).Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Advanced.Days", n)))];
[.. With(RetentionPresets, Applied.RetentionDays).Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Advanced.Days", n)))];
public SettingsOption<int> SelectedRetention
{
get => RetentionChoices.First(c => c.Value == settings.LogRetentionDays);
get => Selected(RetentionChoices, Applied.RetentionDays);
set => Store(value, settings.LogRetentionDays, v => settings.LogRetentionDays = v);
}
public IReadOnlyList<SettingsOption<int>> FileSizeChoices => Sizes(FileSizePresets, settings.LogMaxFileMb);
public IReadOnlyList<SettingsOption<int>> FileSizeChoices
{
get
{
var applied = Applied;
return Sizes(FileSizePresets, applied.MaxFileMb, n => !LogFileOptions.TotalBelowFile(n, applied.MaxTotalMb));
}
}
public SettingsOption<int> SelectedFileSize
{
get => FileSizeChoices.First(c => c.Value == settings.LogMaxFileMb);
set => Store(value, settings.LogMaxFileMb, v => settings.LogMaxFileMb = v);
get => Selected(FileSizeChoices, Applied.MaxFileMb);
set
{
// The totals offered depend on the file size.
if (Store(value, settings.LogMaxFileMb, v => settings.LogMaxFileMb = v)) Changed(nameof(TotalSizeChoices), nameof(SelectedTotalSize));
}
}
public IReadOnlyList<SettingsOption<int>> TotalSizeChoices => Sizes(TotalSizePresets, settings.LogMaxTotalMb);
public IReadOnlyList<SettingsOption<int>> TotalSizeChoices
{
get
{
var applied = Applied;
return Sizes(TotalSizePresets, applied.MaxTotalMb, n => !LogFileOptions.TotalBelowFile(applied.MaxFileMb, n));
}
}
public SettingsOption<int> SelectedTotalSize
{
get => TotalSizeChoices.First(c => c.Value == settings.LogMaxTotalMb);
set => Store(value, settings.LogMaxTotalMb, v => settings.LogMaxTotalMb = v);
get => Selected(TotalSizeChoices, Applied.MaxTotalMb);
set
{
if (Store(value, settings.LogMaxTotalMb, v => settings.LogMaxTotalMb = v)) Changed(nameof(FileSizeChoices), nameof(SelectedFileSize));
}
}
public IReadOnlyList<SettingsOption<LogRotation>> Rotations =>
@@ -62,11 +85,11 @@ public sealed class LogSettingsRows(AppSettings settings, Action save) : Observa
}
public IReadOnlyList<SettingsOption<int>> DiagnosticsChoices =>
[.. With(DiagnosticsPresets, settings.DiagnosticsLogMb).Select(n => new SettingsOption<int>(n, Megabytes(n)))];
[.. With(DiagnosticsPresets, AppliedDiagnosticsMb).Select(n => new SettingsOption<int>(n, Megabytes(n)))];
public SettingsOption<int> SelectedDiagnostics
{
get => DiagnosticsChoices.First(c => c.Value == settings.DiagnosticsLogMb);
get => Selected(DiagnosticsChoices, AppliedDiagnosticsMb);
set => Store(value, settings.DiagnosticsLogMb, v => settings.DiagnosticsLogMb = v);
}
@@ -86,18 +109,39 @@ public sealed class LogSettingsRows(AppSettings settings, Action save) : Observa
/// <summary>Labels in the current language, values as the settings have them now.</summary>
internal void Refresh() => OnAllPropertiesChanged();
private void Store<T>(SettingsOption<T>? choice, T current, Action<T> set, [System.Runtime.CompilerServices.CallerMemberName] string? property = null)
/// <summary>The values the log files get from the settings now.</summary>
private LogFileOptions Applied => AppLogging.Options(settings);
private int AppliedDiagnosticsMb => (int)(AppLogging.DiagnosticsTailBytes(settings) / LogFileOptions.BytesPerMb);
/// <summary>
/// Stores a choice that differs from the stored value (<paramref name="current"/>, which may lie out of range: choosing
/// the value shown then saves it as applied) and saves; false when there was nothing to store.
/// </summary>
private bool Store<T>(SettingsOption<T>? choice, T current, Action<T> set, [System.Runtime.CompilerServices.CallerMemberName] string? property = null)
{
if (choice is null || EqualityComparer<T>.Default.Equals(choice.Value, current)) return;
if (choice is null || EqualityComparer<T>.Default.Equals(choice.Value, current)) return false;
set(choice.Value);
save();
OnPropertyChanged(property);
return true;
}
/// <summary>The presets in order, then "No limit" (0); <paramref name="current"/> joins them when it is another size.</summary>
private static IReadOnlyList<SettingsOption<int>> Sizes(int[] presets, int current) =>
private void Changed(string choices, string selected)
{
OnPropertyChanged(choices);
OnPropertyChanged(selected);
}
private static SettingsOption<int> Selected(IReadOnlyList<SettingsOption<int>> choices, int value) => choices.FirstOrDefault(c => c.Value == value) ?? choices[0];
/// <summary>
/// The presets <paramref name="offered"/> in order, then "No limit" (0); <paramref name="current"/> joins them when it
/// is another size.
/// </summary>
private static IReadOnlyList<SettingsOption<int>> Sizes(int[] presets, int current, Func<int, bool> offered) =>
[
.. With(presets, current).Where(n => n > 0).Select(n => new SettingsOption<int>(n, Megabytes(n))),
.. With(presets.Where(offered).ToArray(), current).Where(n => n > 0).Select(n => new SettingsOption<int>(n, Megabytes(n))),
new(0, Loc.L("Settings.Advanced.NoLimit")),
];
@@ -39,6 +39,12 @@ public sealed record LogFileOptions
public int MaxTotalMb { get; init; } = DefaultMaxTotalMb;
public LogRotation Rotation { get; init; } = LogRotation.Daily;
/// <summary>
/// Whether a total of <paramref name="maxTotalMb"/> is below one file of <paramref name="maxFileMb"/>: each finished file
/// would be deleted as soon as the next one opens. The server refuses such settings; the desktop raises the total.
/// </summary>
public static bool TotalBelowFile(int maxFileMb, int maxTotalMb) => maxTotalMb > 0 && maxFileMb > maxTotalMb;
}
/// <summary>
+3 -1
View File
@@ -2,7 +2,8 @@ namespace Chronos.Protocol;
/// <summary>
/// <c>GET/PUT /api/v1/server/settings</c> (admin): the editable part of the server configuration. Settings named in
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="RestartRequired"/> says
/// <see cref="Locked"/> come from environment variables and cannot be changed here; <see cref="LockedBy"/> names the
/// variable that fixes each of them (ignored when saving); <see cref="RestartRequired"/> says
/// that saved values (ports, TLS, chunk size) wait for a restart; <see cref="JobHistoryDays"/> is what the housekeeping
/// schedule is reset to (owner review 2, R10). <see cref="ProxyWarning"/> is set in responses when TLS mode is proxy and
/// the request did not come through a trusted proxy over HTTPS (ignored when saving).
@@ -29,6 +30,7 @@ public sealed record ServerSettingsDto(
int UploadRetentionHours,
LogSettingsDto Logs,
IReadOnlyList<string> Locked,
IReadOnlyDictionary<string, string> LockedBy,
bool RestartRequired,
bool ProxyWarning);
+6 -13
View File
@@ -9,16 +9,6 @@ import { t, applyStrings, languages } from "../i18n.js";
import { escapeHtml, attr, toast, errorText, nativeName, fingerprint, formatDuration, markInvalid, clearInvalid, invalidText, escapeReverts, routeParams, PROXY_WARNING } from "../ui.js";
import { kindLabel } from "../jobs.js";
/** Setting → environment variable that can fix it (BRIEF §14.9). */
const VARIABLES = {
serverName: "CHRONOS_SERVER_NAME", httpPort: "CHRONOS_HTTP_PORT", httpsPort: "CHRONOS_HTTPS_PORT", tlsMode: "CHRONOS_TLS_MODE",
tlsCert: "CHRONOS_TLS_CERT", tlsKey: "CHRONOS_TLS_KEY", language: "CHRONOS_LANG", parallelism: "CHRONOS_PARALLELISM", discovery: "CHRONOS_DISCOVERY",
priorityQueue: "CHRONOS_PRIORITY_QUEUE", logLevel: "CHRONOS_LOG_LEVEL", logRetentionDays: "CHRONOS_LOG_RETENTION_DAYS",
logMaxFileMb: "CHRONOS_LOG_MAX_FILE_MB", logMaxTotalMb: "CHRONOS_LOG_MAX_TOTAL_MB", logRotation: "CHRONOS_LOG_ROTATION",
auditRetentionDays: "CHRONOS_AUDIT_RETENTION_DAYS", diagnosticsLogMb: "CHRONOS_DIAGNOSTICS_LOG_MB",
// CHRONOS_LOG_LEVEL sets the console's level too, unless CHRONOS_LOG_CONSOLE_LEVEL sets its own.
consoleLogLevel: ["CHRONOS_LOG_CONSOLE_LEVEL", "CHRONOS_LOG_LEVEL"],
};
/** Levels of the priority queue, highest first. */
const LEVELS = ["high", "normal", "low"];
/** Log levels, least severe first (the server's wire names). */
@@ -47,9 +37,12 @@ export async function render(root, { api, info, setMeta, actions }) {
actions.innerHTML = `<button class="btn primary" type="submit" form="settings-form" data-i18n="Admin.Common.Save" data-i18n-title="Admin.Common.Save.Tip"></button>`;
applyStrings(actions);
const locked = (name) => settings.locked.some((l) => l.toLowerCase() === name.toLowerCase());
const lockedTip = (variable) => Array.isArray(variable) ? t("Admin.Settings.LockedEither.Tip", variable[0], variable[1]) : t("Admin.Settings.Locked.Tip", variable);
const lock = (name) => locked(name) ? `disabled title="${attr(lockedTip(VARIABLES[name] ?? name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
const locked = (name) => settings.locked.some((l) => same(l, name));
// The server names the variable that fixes each locked setting: CHRONOS_LOG_LEVEL fixes the console's level too, unless
// CHRONOS_LOG_CONSOLE_LEVEL sets its own (BRIEF §14.9).
const variable = (name) => Object.entries(settings.lockedBy ?? {}).find(([setting]) => same(setting, name))?.[1] ?? name;
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", variable(name)))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
const field = (name, input) => `<label class="field"><span data-i18n="Admin.Settings.${cap(name)}"></span>${input}</label>`;
const number = (name, value, attrs = "") => field(name, `<input class="input narrow num" type="number" name="${name}" value="${attr(value)}" ${attrs} ${lock(name)}>`);
const text = (name, value, attrs = "dir=\"auto\"") => field(name, `<input class="input" name="${name}" value="${attr(value ?? "")}" ${attrs} ${lock(name)}>`);
@@ -88,6 +88,9 @@ public sealed class ServerOptions
/// </summary>
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128";
/// <summary>The environment variable that sets <paramref name="setting"/> (of two, the one that wins), or null.</summary>
public static string? VariableOf(string setting) => Variables.LastOrDefault(v => v.Setting == setting).Variable;
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Distinct(StringComparer.Ordinal).Prepend("CHRONOS_DATA_PATH");
@@ -248,6 +251,13 @@ public sealed class ServerOptions
[JsonIgnore]
public IReadOnlyCollection<string> Locked { get; internal set; } = [];
/// <summary>
/// The environment variable that fixes each setting of <see cref="Locked"/>, which the admin panel names: of two that
/// set one (<c>CHRONOS_LOG_LEVEL</c> and <c>CHRONOS_LOG_CONSOLE_LEVEL</c>), the one that wins.
/// </summary>
[JsonIgnore]
public IReadOnlyDictionary<string, string> LockedBy { get; internal set; } = new Dictionary<string, string>(StringComparer.Ordinal);
[JsonIgnore]
public string LogPath => Path.Combine(DataPath, "logs");
@@ -292,6 +302,7 @@ public sealed class ServerOptions
options.DataPath = dataPath;
var locked = new List<string>();
var lockedBy = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var (variable, setting, apply) in Variables)
{
if (Env(variable) is not { } value) continue;
@@ -304,8 +315,11 @@ public sealed class ServerOptions
throw new InvalidOperationException($"{variable} has an invalid value.", ex);
}
locked.Add(setting);
// Listed in the order they apply: a later variable wins.
lockedBy[setting] = variable;
}
options.Locked = [.. locked.Distinct(StringComparer.Ordinal)];
options.LockedBy = lockedBy;
// The admin panel saves only values it accepts: one it cannot change (an environment variable) must be one of them.
options.Parallelism = Math.Clamp(options.Parallelism, 1, MaxParallelism);
options.Validate();
@@ -89,6 +89,7 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
JobPriorities = Priorities(PriorityQueue(options)),
Logs = Logs(options),
Locked = [.. options.Locked],
LockedBy = LockedBy(options),
RestartRequired = restart,
ProxyWarning = false,
};
@@ -99,7 +100,11 @@ public sealed class ServerSettingsStore(ServerOptions options, ServerLogging log
private static ServerSettingsDto Snapshot(ServerOptions o, bool restartRequired) => new(
o.ServerName, o.HttpPort, o.HttpsPort, o.TlsMode.ToString().ToLowerInvariant(), o.TlsCert, o.TlsKey, o.Language, o.Parallelism, o.PriorityQueue,
Priorities(PriorityQueue(o)), o.Discovery, o.MaxUploadBytes, o.ChunkSizeBytes, o.JobHistoryDays, o.TokenLifetimeDays, o.UploadRetentionHours,
Logs(o), [.. o.Locked], restartRequired, ProxyWarning: false);
Logs(o), [.. o.Locked], LockedBy(o), restartRequired, ProxyWarning: false);
/// <summary>The variable that fixes every locked setting (for one a test locks directly, the variable that would).</summary>
private static Dictionary<string, string> LockedBy(ServerOptions o) => o.Locked.Distinct(StringComparer.Ordinal).ToDictionary(s => s,
s => o.LockedBy.TryGetValue(s, out var variable) ? variable : ServerOptions.VariableOf(s) ?? s, StringComparer.Ordinal);
private static LogSettingsDto Logs(ServerOptions o) => new(ServerLogging.Wire(o.LogLevel), ServerLogging.Wire(o.ConsoleLogLevel), o.LogRetentionDays,
o.LogMaxFileMb, o.LogMaxTotalMb, ServerLogging.Wire(o.LogRotation), o.AuditRetentionDays, o.DiagnosticsLogMb);
+1 -2
View File
@@ -149,8 +149,7 @@ public sealed class ServerLogging
{
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 (maxTotalMb is < 0 or > MaxTotalMb || LogFileOptions.TotalBelowFile(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;