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

+40 -6
View File
@@ -1,7 +1,8 @@
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention. Values fixed by environment
// variables are read-only here; ports, TLS, chunk size and job history apply at the next restart. Jobs run one at a time
// (owner review 1): the parallelism (photos at once) and the priority queue apply at once. About (version, API, database,
// uptime) is the last group, read-only (owner review 2); #/about opens here on it.
// Settings (BRIEF §14.8): server name, ports, TLS, discovery, jobs, limits, language, retention, logs. Values fixed by
// environment variables are read-only here; ports, TLS, chunk size and job history apply at the next restart. Jobs run one
// at a time (owner review 1): the parallelism (photos at once) and the priority queue apply at once, as do the log levels,
// retention, size limits and rotation (owner review 2, R11). About (version, API, database, uptime) is the last group,
// read-only (owner review 2); #/about opens here on it.
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";
@@ -10,10 +11,17 @@ import { kindLabel } from "../jobs.js";
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",
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). */
const LOG_LEVELS = ["trace", "debug", "information", "warning", "error", "critical", "none"];
const ROTATIONS = ["daily", "hourly"];
/** Settings the server names in error details whose field here has another name. */
const FIELDS = { maxuploadbytes: "maxUploadMb", chunksizebytes: "chunkSizeMib" };
const PEM_FILES = ["tlsCert", "tlsKey"];
@@ -38,10 +46,15 @@ export async function render(root, { api, info, setMeta, actions }) {
applyStrings(actions);
const locked = (name) => settings.locked.some((l) => l.toLowerCase() === name.toLowerCase());
const lock = (name) => locked(name) ? `disabled title="${attr(t("Admin.Settings.Locked.Tip", VARIABLES[name] ?? name))}"` : `data-i18n-title="Admin.Settings.${cap(name)}.Tip"`;
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 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)}>`);
// A value this page does not know stays listed, so saving the other settings never changes it.
const choice = (name, value, values, label) => field(name, `<select class="input" name="${name}" ${lock(name)}>${values.concat(values.includes(value) ? [] : [value])
.map((v) => `<option value="${attr(v)}" ${v === value ? "selected" : ""}>${escapeHtml(t(label(v)))}</option>`).join("")}</select>`);
const level = (name, value) => choice(name, value, LOG_LEVELS, (l) => `Admin.Settings.Level.${cap(l)}`);
function draw() {
root.innerHTML = `
@@ -83,6 +96,17 @@ export async function render(root, { api, info, setMeta, actions }) {
${number("uploadRetentionHours", settings.uploadRetentionHours, 'min="1" max="8760"')}
${number("jobHistoryDays", settings.jobHistoryDays, 'min="1" max="3650"')}
</section>
<section class="panel" aria-labelledby="logs-title">
<h2 id="logs-title" data-i18n="Admin.Settings.Logs"></h2>
${level("logLevel", settings.logs.fileLevel)}
${level("consoleLogLevel", settings.logs.consoleLevel)}
${number("logRetentionDays", settings.logs.retentionDays, 'min="1" max="3650"')}
${number("logMaxFileMb", settings.logs.maxFileMb, 'min="0" max="10240"')}
${number("logMaxTotalMb", settings.logs.maxTotalMb, 'min="0" max="1048576"')}
${choice("logRotation", settings.logs.rotation, ROTATIONS, (r) => `Admin.Settings.Rotation.${cap(r)}`)}
${number("auditRetentionDays", settings.logs.auditRetentionDays, 'min="0" max="36500"')}
${number("diagnosticsLogMb", settings.logs.diagnosticsLogMb, 'min="1" max="1024"')}
</section>
</form>
${about()}`;
applyStrings(root);
@@ -157,6 +181,16 @@ export async function render(root, { api, info, setMeta, actions }) {
tokenLifetimeDays: Number(data.get("tokenLifetimeDays")),
uploadRetentionHours: Number(data.get("uploadRetentionHours")),
jobHistoryDays: Number(data.get("jobHistoryDays")),
logs: {
fileLevel: String(value("logLevel", settings.logs.fileLevel)),
consoleLevel: String(value("consoleLogLevel", settings.logs.consoleLevel)),
retentionDays: Number(value("logRetentionDays", settings.logs.retentionDays)),
maxFileMb: Number(value("logMaxFileMb", settings.logs.maxFileMb)),
maxTotalMb: Number(value("logMaxTotalMb", settings.logs.maxTotalMb)),
rotation: String(value("logRotation", settings.logs.rotation)),
auditRetentionDays: Number(value("auditRetentionDays", settings.logs.auditRetentionDays)),
diagnosticsLogMb: Number(value("diagnosticsLogMb", settings.logs.diagnosticsLogMb)),
},
};
try {
settings = await api.put("/api/v1/server/settings", request);
@@ -50,7 +50,7 @@ public static class DiagnosticsEndpoints
bundle.AddJson("settings.json", settings);
bundle.AddText("encoders.txt", encoders);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(options.LogPath, cancellationToken: ct);
bundle.AddLogs(options.LogPath, tailBytes: options.DiagnosticsLogMb * LogFileOptions.BytesPerMb, cancellationToken: ct);
}, ct);
file.Position = 0;
}
@@ -4,6 +4,8 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Data;
using Chronos.Server.Hosting;
using LogFileOptions = Chronos.Core.Diagnostics.LogFileOptions;
using LogRotation = Chronos.Core.Diagnostics.LogRotation;
namespace Chronos.Server.Configuration;
@@ -65,7 +67,16 @@ public sealed class ServerOptions
("CHRONOS_PARALLELISM", nameof(Parallelism), (o, v) => o.Parallelism = Int("CHRONOS_PARALLELISM", v)),
("CHRONOS_PRIORITY_QUEUE", nameof(PriorityQueue), (o, v) => o.PriorityQueue = bool.Parse(v)),
("CHRONOS_DISCOVERY", nameof(Discovery), (o, v) => o.Discovery = bool.Parse(v)),
("CHRONOS_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = Enum.Parse<LogLevel>(v, ignoreCase: true)),
// The level of the files and, unless CHRONOS_LOG_CONSOLE_LEVEL (listed after it) sets its own, of the console.
("CHRONOS_LOG_LEVEL", nameof(LogLevel), (o, v) => o.LogLevel = ServerLogging.ParseLevel("CHRONOS_LOG_LEVEL", v)),
("CHRONOS_LOG_LEVEL", nameof(ConsoleLogLevel), (o, v) => o.ConsoleLogLevel = ServerLogging.ParseLevel("CHRONOS_LOG_LEVEL", v)),
("CHRONOS_LOG_CONSOLE_LEVEL", nameof(ConsoleLogLevel), (o, v) => o.ConsoleLogLevel = ServerLogging.ParseLevel("CHRONOS_LOG_CONSOLE_LEVEL", v)),
("CHRONOS_LOG_RETENTION_DAYS", nameof(LogRetentionDays), (o, v) => o.LogRetentionDays = Int("CHRONOS_LOG_RETENTION_DAYS", v)),
("CHRONOS_LOG_MAX_FILE_MB", nameof(LogMaxFileMb), (o, v) => o.LogMaxFileMb = Int("CHRONOS_LOG_MAX_FILE_MB", v)),
("CHRONOS_LOG_MAX_TOTAL_MB", nameof(LogMaxTotalMb), (o, v) => o.LogMaxTotalMb = Int("CHRONOS_LOG_MAX_TOTAL_MB", v)),
("CHRONOS_LOG_ROTATION", nameof(LogRotation), (o, v) => o.LogRotation = ServerLogging.ParseRotation("CHRONOS_LOG_ROTATION", v)),
("CHRONOS_AUDIT_RETENTION_DAYS", nameof(AuditRetentionDays), (o, v) => o.AuditRetentionDays = Int("CHRONOS_AUDIT_RETENTION_DAYS", v)),
("CHRONOS_DIAGNOSTICS_LOG_MB", nameof(DiagnosticsLogMb), (o, v) => o.DiagnosticsLogMb = Int("CHRONOS_DIAGNOSTICS_LOG_MB", v)),
];
/// <summary>
@@ -77,7 +88,7 @@ public sealed class ServerOptions
public const string DefaultTrustedProxies = "127.0.0.0/8, ::1/128";
/// <summary>The environment variables the server reads (<c>--help</c> lists them all).</summary>
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Prepend("CHRONOS_DATA_PATH");
public static IEnumerable<string> EnvironmentVariables => Variables.Select(v => v.Variable).Distinct(StringComparer.Ordinal).Prepend("CHRONOS_DATA_PATH");
public string ServerName { get; set; } = "Chronos Server";
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\ChronosArchive" : "/archive";
@@ -167,8 +178,32 @@ public sealed class ServerOptions
public bool FormerWorkersVariable { get; private set; }
public bool Discovery { get; set; } = true;
/// <summary>Least severe level written to the console and the log files.</summary>
/// <summary>
/// Least severe level written to the log files (<c>/data/logs</c>); <c>CHRONOS_LOG_LEVEL</c> also sets the console's.
/// Owner review 2, R11: before, the files never took lines below Information whatever this said.
/// </summary>
public LogLevel LogLevel { get; set; } = LogLevel.Information;
/// <summary>Least severe level written to the console (the container's log).</summary>
public LogLevel ConsoleLogLevel { get; set; } = LogLevel.Information;
/// <summary>Log files last written longer ago are deleted.</summary>
public int LogRetentionDays { get; set; } = LogFileOptions.DefaultRetentionDays;
/// <summary>A log file this large (MB of 2²⁰ bytes) continues in a numbered one; 0 = no limit.</summary>
public int LogMaxFileMb { get; set; } = LogFileOptions.DefaultMaxFileMb;
/// <summary>While the log files together are larger (MB), the oldest are deleted, never the current one; 0 = no limit.</summary>
public int LogMaxTotalMb { get; set; } = LogFileOptions.DefaultMaxTotalMb;
/// <summary>One log file per UTC day or per hour.</summary>
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
/// <summary>Days audit entries are kept (the scheduler's housekeeping deletes older ones); 0 = forever.</summary>
public int AuditRetentionDays { get; set; }
/// <summary>MB kept from the end of each log file in the diagnostics zip.</summary>
public int DiagnosticsLogMb { get; set; } = (int)(Chronos.Core.Diagnostics.DiagnosticsArchive.DefaultLogTailBytes / LogFileOptions.BytesPerMb);
public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024;
public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024;
public int JobHistoryDays { get; set; } = 90;
@@ -193,7 +228,7 @@ public sealed class ServerOptions
/// <summary>Settings fixed by environment variables (names of the properties above).</summary>
[JsonIgnore]
public IReadOnlyCollection<string> Locked { get; private set; } = [];
public IReadOnlyCollection<string> Locked { get; internal set; } = [];
[JsonIgnore]
public string LogPath => Path.Combine(DataPath, "logs");
@@ -297,6 +332,10 @@ public sealed class ServerOptions
throw new InvalidOperationException("The chunk size must be between 64 KiB and 64 MiB.");
if (MaxUploadBytes < 1 || TokenLifetimeDays < 1 || JobHistoryDays < 1 || UploadRetentionHours < 1)
throw new InvalidOperationException("Upload size, token lifetime, job history and upload retention must be positive.");
if (ServerLogging.Problem(LogRetentionDays, LogMaxFileMb, LogMaxTotalMb, AuditRetentionDays, DiagnosticsLogMb) is { } log)
throw new InvalidOperationException($"{log} is out of range: {ServerLogging.Ranges}.");
if (!ServerLogging.IsLevel(LogLevel) || !ServerLogging.IsLevel(ConsoleLogLevel) || !Enum.IsDefined(LogRotation))
throw new InvalidOperationException("CHRONOS_LOG_LEVEL, CHRONOS_LOG_CONSOLE_LEVEL or CHRONOS_LOG_ROTATION has an unknown value.");
}
/// <summary>The parsed <see cref="TrustedProxies"/>; a single address is a network of one.</summary>
@@ -5,15 +5,18 @@ using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Server.Hosting;
using LogRotation = Chronos.Core.Diagnostics.LogRotation;
namespace Chronos.Server.Configuration;
/// <summary>
/// The admin panel's view of the configuration (BRIEF §14.8 Settings). Saving writes <c>/data/server.json</c> (only the
/// edited keys; secrets and environment values are never written) and applies what can change while running, the
/// parallelism and the priority queue included (owner review 1); ports, TLS, chunk size and job history wait for a restart.
/// parallelism and the priority queue included (owner review 1), and the log settings through <see cref="ServerLogging"/>
/// (owner review 2, R11); ports, TLS, chunk size and job history wait for a restart.
/// </summary>
public sealed class ServerSettingsStore(ServerOptions options)
public sealed class ServerSettingsStore(ServerOptions options, ServerLogging logging)
{
/// <summary>The kinds of job the server runs, in the order the admin panel lists their levels (downloads and uploads are a client's).</summary>
public static IReadOnlyList<JobKind> Kinds { get; } =
@@ -36,6 +39,8 @@ public sealed class ServerSettingsStore(ServerOptions options)
/// <summary>Validates and saves; returns the error code and the offending setting, or null on success.</summary>
public (string Code, string Setting)? Save(ServerSettingsDto request)
{
// A panel without the log group keeps the log settings as they are.
if (request.Logs is null) request = request with { Logs = Current().Logs };
if (Validate(request) is { } invalid) return ("invalid_setting", invalid);
lock (_gate)
{
@@ -60,6 +65,16 @@ public sealed class ServerSettingsStore(ServerOptions options)
options.Parallelism = request.Parallelism;
options.PriorityQueue = request.PriorityQueue;
options.JobPriorities = JobPriorityQueue.Changed(Levels(request.JobPriorities));
var logs = request.Logs;
options.LogLevel = Level(logs.FileLevel);
options.ConsoleLogLevel = Level(logs.ConsoleLevel);
options.LogRetentionDays = logs.RetentionDays;
options.LogMaxFileMb = logs.MaxFileMb;
options.LogMaxTotalMb = logs.MaxTotalMb;
options.LogRotation = Rotation(logs.Rotation);
options.AuditRetentionDays = logs.AuditRetentionDays;
options.DiagnosticsLogMb = logs.DiagnosticsLogMb;
logging.Apply(options);
var restart = request.HttpPort != options.HttpPort || request.HttpsPort != options.HttpsPort
|| !string.Equals(request.TlsMode, options.TlsMode.ToString(), StringComparison.OrdinalIgnoreCase)
|| request.TlsCert != options.TlsCert || request.TlsKey != options.TlsKey
@@ -68,6 +83,7 @@ public sealed class ServerSettingsStore(ServerOptions options)
{
ServerName = request.ServerName.Trim(),
JobPriorities = Priorities(PriorityQueue(options)),
Logs = Logs(options),
Locked = [.. options.Locked],
RestartRequired = restart,
ProxyWarning = false,
@@ -79,7 +95,16 @@ public sealed class ServerSettingsStore(ServerOptions options)
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,
[.. o.Locked], restartRequired, ProxyWarning: false);
Logs(o), [.. o.Locked], restartRequired, ProxyWarning: false);
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);
/// <summary>A level <see cref="Validate"/> has checked.</summary>
private static LogLevel Level(string wire) => ServerLogging.TryParseLevel(wire, out var level) ? level : LogLevel.Information;
/// <summary>A rotation <see cref="Validate"/> has checked.</summary>
private static LogRotation Rotation(string wire) => ServerLogging.TryParseRotation(wire, out var rotation) ? rotation : LogRotation.Daily;
/// <summary>The level of every kind the server runs in <paramref name="queue"/>.</summary>
private static List<JobPriorityDto> Priorities(JobPriorityQueue queue) =>
@@ -113,7 +138,11 @@ public sealed class ServerSettingsStore(ServerOptions options)
if (r.JobHistoryDays is < 1 or > 3650) return nameof(ServerOptions.JobHistoryDays);
if (r.TokenLifetimeDays is < 1 or > 365) return nameof(ServerOptions.TokenLifetimeDays);
if (r.UploadRetentionHours is < 1 or > 8760) return nameof(ServerOptions.UploadRetentionHours);
return null;
var logs = r.Logs;
if (!ServerLogging.TryParseLevel(logs.FileLevel, out _)) return nameof(ServerOptions.LogLevel);
if (!ServerLogging.TryParseLevel(logs.ConsoleLevel, out _)) return nameof(ServerOptions.ConsoleLogLevel);
if (!ServerLogging.TryParseRotation(logs.Rotation, out _)) return nameof(ServerOptions.LogRotation);
return ServerLogging.Problem(logs.RetentionDays, logs.MaxFileMb, logs.MaxTotalMb, logs.AuditRetentionDays, logs.DiagnosticsLogMb);
}
/// <summary>Settings whose value differs, as server.json keys and JSON values.</summary>
@@ -144,6 +173,15 @@ public sealed class ServerSettingsStore(ServerOptions options)
Add(nameof(ServerOptions.JobHistoryDays), a.JobHistoryDays, b.JobHistoryDays, v => JsonValue.Create(v));
Add(nameof(ServerOptions.TokenLifetimeDays), a.TokenLifetimeDays, b.TokenLifetimeDays, v => JsonValue.Create(v));
Add(nameof(ServerOptions.UploadRetentionHours), a.UploadRetentionHours, b.UploadRetentionHours, v => JsonValue.Create(v));
// Levels and the rotation are stored by name, as server.json reads them ("Debug", "Hourly").
Add(nameof(ServerOptions.LogLevel), Level(a.Logs.FileLevel), Level(b.Logs.FileLevel), v => JsonValue.Create(v.ToString()));
Add(nameof(ServerOptions.ConsoleLogLevel), Level(a.Logs.ConsoleLevel), Level(b.Logs.ConsoleLevel), v => JsonValue.Create(v.ToString()));
Add(nameof(ServerOptions.LogRetentionDays), a.Logs.RetentionDays, b.Logs.RetentionDays, v => JsonValue.Create(v));
Add(nameof(ServerOptions.LogMaxFileMb), a.Logs.MaxFileMb, b.Logs.MaxFileMb, v => JsonValue.Create(v));
Add(nameof(ServerOptions.LogMaxTotalMb), a.Logs.MaxTotalMb, b.Logs.MaxTotalMb, v => JsonValue.Create(v));
Add(nameof(ServerOptions.LogRotation), Rotation(a.Logs.Rotation), Rotation(b.Logs.Rotation), v => JsonValue.Create(v.ToString()));
Add(nameof(ServerOptions.AuditRetentionDays), a.Logs.AuditRetentionDays, b.Logs.AuditRetentionDays, v => JsonValue.Create(v));
Add(nameof(ServerOptions.DiagnosticsLogMb), a.Logs.DiagnosticsLogMb, b.Logs.DiagnosticsLogMb, v => JsonValue.Create(v));
return changes;
}
}
@@ -4,31 +4,27 @@ using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Chronos.Server.Hosting;
/// <summary>In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs).</summary>
public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider
/// <summary>
/// In-house structured file logging for ASP.NET Core: the rotating files of <see cref="ServerLogging.Sink"/> under
/// /data/logs, at <see cref="ServerLogging.FileLevel"/> of the moment (owner review 2, R11: it was fixed at Information,
/// so Debug and Trace never reached the files).
/// </summary>
public sealed class FileLoggerProvider(ServerLogging logging) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName);
public ILogger CreateLogger(string categoryName) => new FileLogger(logging, categoryName);
public void Dispose() => sink.Dispose();
public void Dispose() => logging.Sink.Dispose();
private sealed class FileLogger(FileLogSink sink, string category) : ILogger
private sealed class FileLogger(ServerLogging logging, string category) : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information;
public bool IsEnabled(MsLogLevel logLevel) => logLevel != MsLogLevel.None && logLevel >= logging.FileLevel;
public void Log<TState>(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel)) return;
var level = logLevel switch
{
MsLogLevel.Trace => CoreLogLevel.Trace,
MsLogLevel.Debug => CoreLogLevel.Debug,
MsLogLevel.Information => CoreLogLevel.Info,
MsLogLevel.Warning => CoreLogLevel.Warning,
_ => CoreLogLevel.Error,
};
sink.Write(level, category, formatter(state, exception), exception);
logging.Sink.Write(ServerLogging.Core(logLevel), category, formatter(state, exception), exception);
}
}
}
@@ -42,7 +42,15 @@ public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<stri
CHRONOS_PARALLELISM photos the running job processes at once (jobs run one at a time; default: half the
cores); CHRONOS_WORKERS, its former name, still sets it
CHRONOS_PRIORITY_QUEUE a job of a higher level pauses the running one, which resumes afterwards (true | false)
CHRONOS_LOG_LEVEL (Trace | Debug | Information | Warning | Error)
CHRONOS_LOG_LEVEL least severe level of the log files and the console (Trace | Debug | Information |
Warning | Error | Critical | None; default Information)
CHRONOS_LOG_CONSOLE_LEVEL the console's own level (default: CHRONOS_LOG_LEVEL's)
CHRONOS_LOG_RETENTION_DAYS days log files are kept (default 14)
CHRONOS_LOG_MAX_FILE_MB size at which a log file continues in a numbered one (default 50; 0: no limit)
CHRONOS_LOG_MAX_TOTAL_MB size of all log files; beyond it the oldest are deleted (default 1024; 0: no limit)
CHRONOS_LOG_ROTATION a new log file every day or every hour, UTC (daily | hourly; default daily)
CHRONOS_AUDIT_RETENTION_DAYS days audit entries are kept (default 0: forever)
CHRONOS_DIAGNOSTICS_LOG_MB MB from the end of each log file in the diagnostics zip (default 4)
CHRONOS_DISCOVERY LAN beacon (true | false); in a container it needs host networking
CHRONOS_PUBLIC_HTTP_PORT, CHRONOS_PUBLIC_HTTPS_PORT
ports clients reach when the container's ports are published as other host ports
+5 -7
View File
@@ -36,18 +36,16 @@ public static class ServerHost
var archiveOpenToOthers = DataFolderAccess.PrepareArchive(options.ArchivePath);
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(options.LogLevel);
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", options.LogLevel > Microsoft.Extensions.Logging.LogLevel.Information ? options.LogLevel : Microsoft.Extensions.Logging.LogLevel.Information);
// The console and the files each follow their own level, which the admin panel changes while the server runs.
var logging = new ServerLogging(options);
logging.AddTo(builder.Logging);
builder.Services.AddSingleton(logging);
// The archive module registers first, so a missing piece stops the server before it touches the database.
configureServices?.Invoke(builder.Services);
RequireArchiveModule(builder.Services);
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.LogLevel));
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true).SetMinimumLevel(options.ConsoleLogLevel));
var bootLogger = bootLoggerFactory.CreateLogger("Chronos.Server");
var certificate = CertificateStore.Load(options, bootLogger);
var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
+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;
}
}