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

+12 -1
View File
@@ -42,8 +42,19 @@ services:
# admin panel's Settings.
# CHRONOS_PARALLELISM: "4"
# CHRONOS_PRIORITY_QUEUE: "true"
# Trace, Debug, Information, Warning or Error
# The log files' and the console's level: Trace, Debug, Information, Warning, Error, Critical or None
CHRONOS_LOG_LEVEL: Information
# The log files (/data/logs) and the audit log: the console's own level, the days files are kept, the size (MB) at
# which a file continues in a numbered one and that of all files (the oldest go beyond it; 0: no limit for either),
# daily or hourly files, the days audit entries are kept (0: forever) and the MB of each log in the diagnostics zip.
# Set here, they can no longer be changed in the admin panel's Settings › Logs.
# CHRONOS_LOG_CONSOLE_LEVEL: Warning
# CHRONOS_LOG_RETENTION_DAYS: "14"
# CHRONOS_LOG_MAX_FILE_MB: "50"
# CHRONOS_LOG_MAX_TOTAL_MB: "1024"
# CHRONOS_LOG_ROTATION: daily
# CHRONOS_AUDIT_RETENTION_DAYS: "0"
# CHRONOS_DIAGNOSTICS_LOG_MB: "4"
# The admin panel shows the archive volume's free space. An Unraid share (/mnt/user/<share>) reports its primary
# storage, often the cache: map the share's array view to /space (volumes below) and show that one instead.
# CHRONOS_SPACE_PATH: /space
+5
View File
@@ -87,6 +87,11 @@ admin panel shows under Settings so you can compare them.
- Upgrade: `docker compose pull && docker compose up -d`. Jobs in progress resume from their last checkpoint.
- All settings: environment variables `CHRONOS_*` (see `docker-compose.yml`) or `/data/server.json`. Run
`docker run --rm gitea.encke-hake.ts.net/balbosoft/chronos-server:latest --help` for the list.
- Logs: `/data/logs/server-yyyyMMdd.log`, or one file per hour with `CHRONOS_LOG_ROTATION=hourly` (UTC). A file
continues in `.1.log`, `.2.log`… at 50 MB (`CHRONOS_LOG_MAX_FILE_MB`), files are kept 14 days
(`CHRONOS_LOG_RETENTION_DAYS`) and the oldest go when all of them pass 1024 MB (`CHRONOS_LOG_MAX_TOTAL_MB`; 0: no
limit). `CHRONOS_LOG_LEVEL` sets the level of the files and the console, `CHRONOS_LOG_CONSOLE_LEVEL` the console's
alone. Without these variables the admin panel changes them in Settings › Logs while the server runs.
- Other host ports: when you publish the container's ports as other host ports (`18443:8443`), set
`CHRONOS_PUBLIC_HTTPS_PORT` (and `CHRONOS_PUBLIC_HTTP_PORT`) to the host ports, so the admin panel's redirect to HTTPS
and LAN discovery name the ports clients can reach.
+8 -1
View File
@@ -41,7 +41,14 @@
<Config Name="Server name" Target="CHRONOS_SERVER_NAME" Default="Chronos Server" Mode="" Description="Name shown to clients." Type="Variable" Display="advanced" Required="false" Mask="false">Chronos Server</Config>
<Config Name="Parallelism" Target="CHRONOS_PARALLELISM" Default="" Mode="" Description="Jobs run one at a time: photos the running job processes at once (empty: half the cores, changeable in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Priority queue" Target="CHRONOS_PRIORITY_QUEUE" Default="" Mode="" Description="true: a job of a higher kind pauses the running one, which resumes afterwards (empty: set it in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Log level" Target="CHRONOS_LOG_LEVEL" Default="Information" Mode="" Description="Trace, Debug, Information, Warning or Error." Type="Variable" Display="advanced" Required="false" Mask="false">Information</Config>
<Config Name="Log level" Target="CHRONOS_LOG_LEVEL" Default="Information" Mode="" Description="Level of the log files and, unless Console log level is set, of the container's log: Trace, Debug, Information, Warning, Error, Critical or None." Type="Variable" Display="advanced" Required="false" Mask="false">Information</Config>
<Config Name="Console log level" Target="CHRONOS_LOG_CONSOLE_LEVEL" Default="" Mode="" Description="Level of the container's log alone (empty: the Log level's)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Log retention" Target="CHRONOS_LOG_RETENTION_DAYS" Default="" Mode="" Description="Days the log files in /data/logs are kept (empty: 14, changeable in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Log file size" Target="CHRONOS_LOG_MAX_FILE_MB" Default="" Mode="" Description="MB at which a log file continues in a numbered one; 0: no limit (empty: 50, changeable in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Logs total size" Target="CHRONOS_LOG_MAX_TOTAL_MB" Default="" Mode="" Description="MB all log files may take, the oldest deleted beyond it; 0: no limit (empty: 1024, changeable in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Log rotation" Target="CHRONOS_LOG_ROTATION" Default="" Mode="" Description="daily or hourly: a new log file every day or every hour, UTC (empty: daily, changeable in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Audit retention" Target="CHRONOS_AUDIT_RETENTION_DAYS" Default="" Mode="" Description="Days audit entries are kept; 0: forever (empty: forever, changeable in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Diagnostics log size" Target="CHRONOS_DIAGNOSTICS_LOG_MB" Default="" Mode="" Description="MB from the end of each log file in the diagnostics zip (empty: 4, changeable in the admin panel)." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="User id that owns files." Type="Variable" Display="advanced" Required="true" Mask="false">99</Config>
<Config Name="PGID" Target="PGID" Default="100" Mode="" Description="Group id that owns files." Type="Variable" Display="advanced" Required="true" Mask="false">100</Config>
<Config Name="Time zone" Target="TZ" Default="Europe/Rome" Mode="" Description="Local time used to name folders of photos without a capture time; logs stay in UTC." Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
+4 -4
View File
@@ -45,7 +45,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Naming` | Folder/file templates and tokens |
| `Model` | Domain entities and enums (§5) shared by Data, Server and clients |
| `Packaging` | TPK1 installer payload writer/reader, staged install transaction |
| `Diagnostics` | `Log`, file sink, synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) |
| `Diagnostics` | `Log`, `FileLogSink` with `LogFileOptions` (level, daily or hourly files, numbered parts past a size, pruning by age and by the total size, never the file being written), synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) |
| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, `StartupCommand` (sign-in entries of the programs, moved or removed by setup), CRC-32/SHA helpers, brand mark geometry |
### 2.2 Chronos.Data
@@ -71,8 +71,8 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) |
| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, mass rename and move, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`), `ArchiveFailures` |
| `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` |
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); settings rows, encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job: parallelism, memory budget, quality), `InterfacePriority`, language catalog, naming preview; `AboutViewModel` (owned by the shell, not a section: Settings › About, the update notice of Settings › Updates and the update check on start), update check and download |
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Chronos per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); settings rows (`LogSettingsRows`: Advanced's log rows), encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job: parallelism, memory budget, quality), `InterfacePriority`, language catalog, naming preview; `AboutViewModel` (owned by the shell, not a section: Settings › About, the update notice of Settings › Updates and the update check on start), update check and download |
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppLogging` (Settings › Advanced › Logs applied to the log files at start and at every save), `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Chronos per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
| `DesignTime` | `SampleData`: the archive, jobs and server the screenshots and smoke tests run on, dated from the fixed `SampleData.Now` |
### 2.4 Chronos.Ui and Chronos.Server
@@ -86,7 +86,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`), API errors, the WebSocket `EventHub` |
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
| `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads, render store; `JobEngineHost`, render node service, monitor and availability |
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page) |
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page) |
### 2.5 Hosts
+27
View File
@@ -274,8 +274,14 @@
<data name="Admin.Role.Uploader" xml:space="preserve"><value>Uploader</value></data>
<data name="Admin.Role.Viewer" xml:space="preserve"><value>Viewer</value></data>
<data name="Admin.Settings.About" xml:space="preserve"><value>About</value></data>
<data name="Admin.Settings.AuditRetentionDays" xml:space="preserve"><value>Keep audit (days)</value></data>
<data name="Admin.Settings.AuditRetentionDays.Tip" xml:space="preserve"><value>Days audit entries are kept before the housekeeping deletes them; 0: forever</value></data>
<data name="Admin.Settings.ChunkSizeMib" xml:space="preserve"><value>Chunk size (MiB)</value></data>
<data name="Admin.Settings.ChunkSizeMib.Tip" xml:space="preserve"><value>Size of each upload chunk; smaller chunks resume faster on poor links</value></data>
<data name="Admin.Settings.ConsoleLogLevel" xml:space="preserve"><value>Console level</value></data>
<data name="Admin.Settings.ConsoleLogLevel.Tip" xml:space="preserve"><value>Least severe level written to the console, the container's log</value></data>
<data name="Admin.Settings.DiagnosticsLogMb" xml:space="preserve"><value>Diagnostics logs (MB)</value></data>
<data name="Admin.Settings.DiagnosticsLogMb.Tip" xml:space="preserve"><value>How much of the end of each log file the diagnostics zip includes</value></data>
<data name="Admin.Settings.Discovery" xml:space="preserve"><value>LAN discovery</value></data>
<data name="Admin.Settings.Discovery.Tip" xml:space="preserve"><value>Announce this server on the local network so clients find it</value></data>
<data name="Admin.Settings.Fingerprint" xml:space="preserve"><value>Fingerprint</value></data>
@@ -290,8 +296,27 @@
<data name="Admin.Settings.Jobs" xml:space="preserve"><value>Jobs</value></data>
<data name="Admin.Settings.Language" xml:space="preserve"><value>Language</value></data>
<data name="Admin.Settings.Language.Tip" xml:space="preserve"><value>Language of server messages when a client asks for none</value></data>
<data name="Admin.Settings.Level.Critical" xml:space="preserve"><value>Critical</value></data>
<data name="Admin.Settings.Level.Debug" xml:space="preserve"><value>Debug</value></data>
<data name="Admin.Settings.Level.Error" xml:space="preserve"><value>Error</value></data>
<data name="Admin.Settings.Level.Information" xml:space="preserve"><value>Information</value></data>
<data name="Admin.Settings.Level.None" xml:space="preserve"><value>Off</value></data>
<data name="Admin.Settings.Level.Trace" xml:space="preserve"><value>Trace</value></data>
<data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Warning</value></data>
<data name="Admin.Settings.Limits" xml:space="preserve"><value>Limits and retention</value></data>
<data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Set by the environment variable {0}</value></data>
<data name="Admin.Settings.LockedEither.Tip" xml:space="preserve"><value>Set by the environment variable {0} or {1}</value></data>
<data name="Admin.Settings.LogLevel" xml:space="preserve"><value>File level</value></data>
<data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Least severe level written to the log files; Debug and Trace help find problems but fill the files fast</value></data>
<data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>File size (MB)</value></data>
<data name="Admin.Settings.LogMaxFileMb.Tip" xml:space="preserve"><value>A log file that reaches this size continues in a new numbered file; 0: no limit</value></data>
<data name="Admin.Settings.LogMaxTotalMb" xml:space="preserve"><value>Logs total (MB)</value></data>
<data name="Admin.Settings.LogMaxTotalMb.Tip" xml:space="preserve"><value>When the log files together exceed this size, the oldest are deleted, never the one being written; 0: no limit</value></data>
<data name="Admin.Settings.LogRetentionDays" xml:space="preserve"><value>Keep logs (days)</value></data>
<data name="Admin.Settings.LogRetentionDays.Tip" xml:space="preserve"><value>Log files last written longer ago are deleted</value></data>
<data name="Admin.Settings.LogRotation" xml:space="preserve"><value>Rotation</value></data>
<data name="Admin.Settings.LogRotation.Tip" xml:space="preserve"><value>Start a new log file every day or every hour (UTC)</value></data>
<data name="Admin.Settings.Logs" xml:space="preserve"><value>Logs</value></data>
<data name="Admin.Settings.MaxUploadMb" xml:space="preserve"><value>Max file (MB)</value></data>
<data name="Admin.Settings.MaxUploadMb.Tip" xml:space="preserve"><value>Largest single upload accepted</value></data>
<data name="Admin.Settings.Network" xml:space="preserve"><value>Network and TLS</value></data>
@@ -308,6 +333,8 @@
<data name="Admin.Settings.ProxyBypassed.Tip" xml:space="preserve"><value>TLS mode is Reverse proxy, but this page did not come through a trusted proxy over HTTPS. Open it through your proxy, or add the proxy's address to CHRONOS_TRUSTED_PROXIES.</value></data>
<data name="Admin.Settings.Restart" xml:space="preserve"><value>Restart required</value></data>
<data name="Admin.Settings.Restart.Tip" xml:space="preserve"><value>Saved ports, TLS, workers, chunk size or job history apply after a restart</value></data>
<data name="Admin.Settings.Rotation.Daily" xml:space="preserve"><value>Daily</value></data>
<data name="Admin.Settings.Rotation.Hourly" xml:space="preserve"><value>Hourly</value></data>
<data name="Admin.Settings.Server" xml:space="preserve"><value>Server</value></data>
<data name="Admin.Settings.ServerName" xml:space="preserve"><value>Server name</value></data>
<data name="Admin.Settings.ServerName.Tip" xml:space="preserve"><value>Name shown to clients and on the LAN</value></data>
+16
View File
@@ -10,13 +10,26 @@
<data name="Settings.Advanced.DataFolder" xml:space="preserve"><value>Data folder</value></data>
<data name="Settings.Advanced.DataInOneDrive" xml:space="preserve"><value>Data inside OneDrive</value></data>
<data name="Settings.Advanced.DataOutsideOneDrive" xml:space="preserve"><value>Data kept outside OneDrive</value><comment>long</comment></data>
<data name="Settings.Advanced.Days.one" xml:space="preserve"><value>{0} day</value></data>
<data name="Settings.Advanced.Days.other" xml:space="preserve"><value>{0} days</value></data>
<data name="Settings.Advanced.Diagnostics" xml:space="preserve"><value>Diagnostics</value></data>
<data name="Settings.Advanced.DiagnosticsDone" xml:space="preserve"><value>Diagnostics bundle saved</value></data>
<data name="Settings.Advanced.DiagnosticsLogs" xml:space="preserve"><value>Diagnostics logs</value></data>
<data name="Settings.Advanced.DiagnosticsTitle" xml:space="preserve"><value>Save the diagnostics bundle to</value></data>
<data name="Settings.Advanced.EarlierData" xml:space="preserve"><value>Earlier data unused</value></data>
<data name="Settings.Advanced.ExportBundle" xml:space="preserve"><value>Export bundle</value></data>
<data name="Settings.Advanced.FileSize" xml:space="preserve"><value>File size</value></data>
<data name="Settings.Advanced.KeepLogs" xml:space="preserve"><value>Keep logs</value></data>
<data name="Settings.Advanced.Level.Debug" xml:space="preserve"><value>Debug</value></data>
<data name="Settings.Advanced.Level.Error" xml:space="preserve"><value>Error</value></data>
<data name="Settings.Advanced.Level.Info" xml:space="preserve"><value>Information</value></data>
<data name="Settings.Advanced.Level.Trace" xml:space="preserve"><value>Trace</value></data>
<data name="Settings.Advanced.Level.Warning" xml:space="preserve"><value>Warning</value></data>
<data name="Settings.Advanced.LogLevel" xml:space="preserve"><value>Log level</value></data>
<data name="Settings.Advanced.Logs" xml:space="preserve"><value>Logs</value></data>
<data name="Settings.Advanced.LogsTotal" xml:space="preserve"><value>Logs total</value></data>
<data name="Settings.Advanced.NoBackups" xml:space="preserve"><value>No backups yet</value></data>
<data name="Settings.Advanced.NoLimit" xml:space="preserve"><value>No limit</value></data>
<data name="Settings.Advanced.Portable" xml:space="preserve"><value>Portable mode</value></data>
<data name="Settings.Advanced.PortableOff" xml:space="preserve"><value>Off</value></data>
<data name="Settings.Advanced.PortableOn" xml:space="preserve"><value>On</value></data>
@@ -40,6 +53,9 @@
<data name="Settings.Advanced.RestoreTitle" xml:space="preserve"><value>Restore the index of {0}?</value><comment>long</comment></data>
<data name="Settings.Advanced.RestoreUnreadable" xml:space="preserve"><value>Now: unreadable</value></data>
<data name="Settings.Advanced.Restored" xml:space="preserve"><value>Index restored from a backup</value><comment>long</comment></data>
<data name="Settings.Advanced.Rotation" xml:space="preserve"><value>Rotation</value></data>
<data name="Settings.Advanced.Rotation.Daily" xml:space="preserve"><value>Daily</value></data>
<data name="Settings.Advanced.Rotation.Hourly" xml:space="preserve"><value>Hourly</value></data>
<data name="Settings.Analysis.AfterImport" xml:space="preserve"><value>After import</value></data>
<data name="Settings.Analysis.AfterScan" xml:space="preserve"><value>After a scan</value></data>
<data name="Settings.Analysis.Deep" xml:space="preserve"><value>Deep analysis</value></data>
+6
View File
@@ -558,6 +558,7 @@
<data name="Tooltips.Settings.DeepAfterScan" xml:space="preserve"><value>Sequences a scan finds (adopted folders, new sidecars) also get a deep analysis, in the background</value></data>
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server Chronos connects to at start; changing it signs out · Enter applies, Esc reverts</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out</value></data>
<data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>How much of the end of each log file the diagnostics bundle includes</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Open the data this portable copy kept beside it before it ran from OneDrive. Chronos no longer uses it and leaves it as it is</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Save every setting as JSON, without the session token</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts</value></data>
@@ -569,9 +570,13 @@
<data name="Tooltips.Settings.KeepArchiveSettings" xml:space="preserve"><value>Leave this archive's settings as they are</value></data>
<data name="Tooltips.Settings.KeepCache" xml:space="preserve"><value>Keep the cache as it is</value></data>
<data name="Tooltips.Settings.KeepIndex" xml:space="preserve"><value>Keep the index as it is</value></data>
<data name="Tooltips.Settings.KeepLogs" xml:space="preserve"><value>Log files last written longer ago are deleted</value></data>
<data name="Tooltips.Settings.KeepSettings" xml:space="preserve"><value>Keep every setting as it is</value></data>
<data name="Tooltips.Settings.Language" xml:space="preserve"><value>Language of the interface · applies immediately</value></data>
<data name="Tooltips.Settings.LogFileSize" xml:space="preserve"><value>A log file that reaches this size continues in a new numbered file</value></data>
<data name="Tooltips.Settings.LogLevel" xml:space="preserve"><value>Least severe level written to the log files; Debug and Trace help find problems but fill the files fast</value></data>
<data name="Tooltips.Settings.LogsFolder" xml:space="preserve"><value>Daily log files, kept for 14 days</value></data>
<data name="Tooltips.Settings.LogsTotal" xml:space="preserve"><value>When the log files together exceed this size, the oldest are deleted, never the one being written</value></data>
<data name="Tooltips.Settings.Memory" xml:space="preserve"><value>Frames stay in memory up to this budget, then spill to the cache folder</value></data>
<data name="Tooltips.Settings.MemoryAuto" xml:space="preserve"><value>Auto: a quarter of installed memory</value></data>
<data name="Tooltips.Settings.MemoryReset" xml:space="preserve"><value>Back to Auto: a quarter of installed memory</value></data>
@@ -611,6 +616,7 @@
<data name="Tooltips.Settings.RestoreCancel" xml:space="preserve"><value>Keep the current index at the next start</value></data>
<data name="Tooltips.Settings.RestoreConfirm" xml:space="preserve"><value>At the next start of Chronos, back up the current index and then restore this backup</value></data>
<data name="Tooltips.Settings.RestorePending" xml:space="preserve"><value>The chosen backup replaces the index when Chronos starts next</value></data>
<data name="Tooltips.Settings.Rotation" xml:space="preserve"><value>Start a new log file every day or every hour (UTC)</value></data>
<data name="Tooltips.Settings.Search" xml:space="preserve"><value>Find a setting by name</value></data>
<data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute</value></data>
<data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Speed on the synthetic 1280×720 test clip</value></data>
+27
View File
@@ -273,8 +273,14 @@
<data name="Admin.Role.Uploader" xml:space="preserve"><value>Caricamento</value></data>
<data name="Admin.Role.Viewer" xml:space="preserve"><value>Lettore</value></data>
<data name="Admin.Settings.About" xml:space="preserve"><value>Informazioni</value></data>
<data name="Admin.Settings.AuditRetentionDays" xml:space="preserve"><value>Conserva controllo (giorni)</value></data>
<data name="Admin.Settings.AuditRetentionDays.Tip" xml:space="preserve"><value>Giorni di conservazione delle voci di controllo prima che la manutenzione le elimini; 0: per sempre</value></data>
<data name="Admin.Settings.ChunkSizeMib" xml:space="preserve"><value>Dimensione blocco (MiB)</value></data>
<data name="Admin.Settings.ChunkSizeMib.Tip" xml:space="preserve"><value>Dimensione di ogni blocco di caricamento; blocchi piccoli riprendono prima su linee lente</value></data>
<data name="Admin.Settings.ConsoleLogLevel" xml:space="preserve"><value>Livello console</value></data>
<data name="Admin.Settings.ConsoleLogLevel.Tip" xml:space="preserve"><value>Livello minimo scritto nella console, il log del container</value></data>
<data name="Admin.Settings.DiagnosticsLogMb" xml:space="preserve"><value>Log diagnostica (MB)</value></data>
<data name="Admin.Settings.DiagnosticsLogMb.Tip" xml:space="preserve"><value>Quanta parte finale di ogni file di log include lo zip di diagnostica</value></data>
<data name="Admin.Settings.Discovery" xml:space="preserve"><value>Rilevamento LAN</value></data>
<data name="Admin.Settings.Discovery.Tip" xml:space="preserve"><value>Annuncia questo server nella rete locale così che i client lo trovino</value></data>
<data name="Admin.Settings.Fingerprint" xml:space="preserve"><value>Impronta</value></data>
@@ -289,8 +295,27 @@
<data name="Admin.Settings.Jobs" xml:space="preserve"><value>Attività</value></data>
<data name="Admin.Settings.Language" xml:space="preserve"><value>Lingua</value></data>
<data name="Admin.Settings.Language.Tip" xml:space="preserve"><value>Lingua dei messaggi del server se il client non ne chiede una</value></data>
<data name="Admin.Settings.Level.Critical" xml:space="preserve"><value>Critico</value></data>
<data name="Admin.Settings.Level.Debug" xml:space="preserve"><value>Debug</value></data>
<data name="Admin.Settings.Level.Error" xml:space="preserve"><value>Errore</value></data>
<data name="Admin.Settings.Level.Information" xml:space="preserve"><value>Informazioni</value></data>
<data name="Admin.Settings.Level.None" xml:space="preserve"><value>Disattivato</value></data>
<data name="Admin.Settings.Level.Trace" xml:space="preserve"><value>Trace</value></data>
<data name="Admin.Settings.Level.Warning" xml:space="preserve"><value>Avviso</value></data>
<data name="Admin.Settings.Limits" xml:space="preserve"><value>Limiti e conservazione</value></data>
<data name="Admin.Settings.Locked.Tip" xml:space="preserve"><value>Impostato dalla variabile d'ambiente {0}</value></data>
<data name="Admin.Settings.LockedEither.Tip" xml:space="preserve"><value>Impostato dalla variabile d'ambiente {0} o {1}</value></data>
<data name="Admin.Settings.LogLevel" xml:space="preserve"><value>Livello file</value></data>
<data name="Admin.Settings.LogLevel.Tip" xml:space="preserve"><value>Livello minimo scritto nei file di log; Debug e Trace aiutano a trovare i problemi ma riempiono i file in fretta</value></data>
<data name="Admin.Settings.LogMaxFileMb" xml:space="preserve"><value>Dimensione file (MB)</value></data>
<data name="Admin.Settings.LogMaxFileMb.Tip" xml:space="preserve"><value>Un file di log che raggiunge questa dimensione prosegue in un nuovo file numerato; 0: nessun limite</value></data>
<data name="Admin.Settings.LogMaxTotalMb" xml:space="preserve"><value>Totale log (MB)</value></data>
<data name="Admin.Settings.LogMaxTotalMb.Tip" xml:space="preserve"><value>Quando i file di log insieme superano questa dimensione, i più vecchi vengono eliminati, mai quello in scrittura; 0: nessun limite</value></data>
<data name="Admin.Settings.LogRetentionDays" xml:space="preserve"><value>Conserva log (giorni)</value></data>
<data name="Admin.Settings.LogRetentionDays.Tip" xml:space="preserve"><value>I file di log scritti l'ultima volta prima di questo periodo vengono eliminati</value></data>
<data name="Admin.Settings.LogRotation" xml:space="preserve"><value>Rotazione</value></data>
<data name="Admin.Settings.LogRotation.Tip" xml:space="preserve"><value>Inizia un nuovo file di log ogni giorno o ogni ora (UTC)</value></data>
<data name="Admin.Settings.Logs" xml:space="preserve"><value>Log</value></data>
<data name="Admin.Settings.MaxUploadMb" xml:space="preserve"><value>File massimo (MB)</value></data>
<data name="Admin.Settings.MaxUploadMb.Tip" xml:space="preserve"><value>Caricamento singolo più grande accettato</value></data>
<data name="Admin.Settings.Network" xml:space="preserve"><value>Rete e TLS</value></data>
@@ -307,6 +332,8 @@
<data name="Admin.Settings.ProxyBypassed.Tip" xml:space="preserve"><value>La modalità TLS è Reverse proxy, ma questa pagina non è arrivata da un proxy attendibile in HTTPS. Aprila tramite il proxy o aggiungi l'indirizzo del proxy a CHRONOS_TRUSTED_PROXIES.</value></data>
<data name="Admin.Settings.Restart" xml:space="preserve"><value>Riavvio richiesto</value></data>
<data name="Admin.Settings.Restart.Tip" xml:space="preserve"><value>Porte, TLS, worker, dimensione blocchi o cronologia job salvati valgono dopo un riavvio</value></data>
<data name="Admin.Settings.Rotation.Daily" xml:space="preserve"><value>Giornaliera</value></data>
<data name="Admin.Settings.Rotation.Hourly" xml:space="preserve"><value>Oraria</value></data>
<data name="Admin.Settings.Server" xml:space="preserve"><value>Server</value></data>
<data name="Admin.Settings.ServerName" xml:space="preserve"><value>Nome server</value></data>
<data name="Admin.Settings.ServerName.Tip" xml:space="preserve"><value>Nome mostrato ai client e nella rete locale</value></data>
+16
View File
@@ -10,13 +10,26 @@
<data name="Settings.Advanced.DataFolder" xml:space="preserve"><value>Cartella dati</value></data>
<data name="Settings.Advanced.DataInOneDrive" xml:space="preserve"><value>Dati dentro OneDrive</value></data>
<data name="Settings.Advanced.DataOutsideOneDrive" xml:space="preserve"><value>Dati tenuti fuori da OneDrive</value></data>
<data name="Settings.Advanced.Days.one" xml:space="preserve"><value>{0} giorno</value></data>
<data name="Settings.Advanced.Days.other" xml:space="preserve"><value>{0} giorni</value></data>
<data name="Settings.Advanced.Diagnostics" xml:space="preserve"><value>Diagnostica</value></data>
<data name="Settings.Advanced.DiagnosticsDone" xml:space="preserve"><value>Pacchetto diagnostico salvato</value></data>
<data name="Settings.Advanced.DiagnosticsLogs" xml:space="preserve"><value>Log diagnostica</value></data>
<data name="Settings.Advanced.DiagnosticsTitle" xml:space="preserve"><value>Salva il pacchetto in</value></data>
<data name="Settings.Advanced.EarlierData" xml:space="preserve"><value>Dati precedenti inutilizzati</value></data>
<data name="Settings.Advanced.ExportBundle" xml:space="preserve"><value>Esporta pacchetto</value></data>
<data name="Settings.Advanced.FileSize" xml:space="preserve"><value>Dimensione file</value></data>
<data name="Settings.Advanced.KeepLogs" xml:space="preserve"><value>Conserva log</value></data>
<data name="Settings.Advanced.Level.Debug" xml:space="preserve"><value>Debug</value></data>
<data name="Settings.Advanced.Level.Error" xml:space="preserve"><value>Errore</value></data>
<data name="Settings.Advanced.Level.Info" xml:space="preserve"><value>Informazioni</value></data>
<data name="Settings.Advanced.Level.Trace" xml:space="preserve"><value>Trace</value></data>
<data name="Settings.Advanced.Level.Warning" xml:space="preserve"><value>Avviso</value></data>
<data name="Settings.Advanced.LogLevel" xml:space="preserve"><value>Livello log</value></data>
<data name="Settings.Advanced.Logs" xml:space="preserve"><value>Log</value></data>
<data name="Settings.Advanced.LogsTotal" xml:space="preserve"><value>Totale log</value></data>
<data name="Settings.Advanced.NoBackups" xml:space="preserve"><value>Ancora nessuna copia</value></data>
<data name="Settings.Advanced.NoLimit" xml:space="preserve"><value>Nessun limite</value></data>
<data name="Settings.Advanced.Portable" xml:space="preserve"><value>Modalità portatile</value></data>
<data name="Settings.Advanced.PortableOff" xml:space="preserve"><value>Disattivata</value></data>
<data name="Settings.Advanced.PortableOn" xml:space="preserve"><value>Attiva</value></data>
@@ -40,6 +53,9 @@
<data name="Settings.Advanced.RestoreTitle" xml:space="preserve"><value>Ripristinare l'indice del {0}?</value></data>
<data name="Settings.Advanced.RestoreUnreadable" xml:space="preserve"><value>Ora: illeggibile</value></data>
<data name="Settings.Advanced.Restored" xml:space="preserve"><value>Indice ripristinato da una copia</value></data>
<data name="Settings.Advanced.Rotation" xml:space="preserve"><value>Rotazione</value></data>
<data name="Settings.Advanced.Rotation.Daily" xml:space="preserve"><value>Giornaliera</value></data>
<data name="Settings.Advanced.Rotation.Hourly" xml:space="preserve"><value>Oraria</value></data>
<data name="Settings.Analysis.AfterImport" xml:space="preserve"><value>Dopo l'importazione</value></data>
<data name="Settings.Analysis.AfterScan" xml:space="preserve"><value>Dopo una scansione</value></data>
<data name="Settings.Analysis.Deep" xml:space="preserve"><value>Analisi profonda</value></data>
+6
View File
@@ -556,6 +556,7 @@
<data name="Tooltips.Settings.DeepAfterScan" xml:space="preserve"><value>Anche le sequenze trovate da una scansione (cartelle adottate, nuovi sidecar) ricevono l'analisi profonda, in background</value></data>
<data name="Tooltips.Settings.DefaultServer" xml:space="preserve"><value>Server a cui Chronos si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla</value></data>
<data name="Tooltips.Settings.Diagnostics" xml:space="preserve"><value>Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori</value></data>
<data name="Tooltips.Settings.DiagnosticsLogs" xml:space="preserve"><value>Quanta parte finale di ogni file di log include il pacchetto di diagnostica</value></data>
<data name="Tooltips.Settings.EarlierData" xml:space="preserve"><value>Apri i dati che questa copia portatile teneva accanto a sé prima di trovarsi in OneDrive. Chronos non li usa più e li lascia com'erano</value></data>
<data name="Tooltips.Settings.Export" xml:space="preserve"><value>Salva tutte le impostazioni in JSON, senza il token di sessione</value></data>
<data name="Tooltips.Settings.FileTemplate" xml:space="preserve"><value>Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla</value></data>
@@ -567,9 +568,13 @@
<data name="Tooltips.Settings.KeepArchiveSettings" xml:space="preserve"><value>Lascia le impostazioni dell'archivio come sono</value></data>
<data name="Tooltips.Settings.KeepCache" xml:space="preserve"><value>Lascia la cache com'è</value></data>
<data name="Tooltips.Settings.KeepIndex" xml:space="preserve"><value>Lascia l'indice com'è</value></data>
<data name="Tooltips.Settings.KeepLogs" xml:space="preserve"><value>I file di log scritti l'ultima volta prima di questo periodo vengono eliminati</value></data>
<data name="Tooltips.Settings.KeepSettings" xml:space="preserve"><value>Lascia ogni impostazione com'è</value></data>
<data name="Tooltips.Settings.Language" xml:space="preserve"><value>Lingua dell'interfaccia · si applica subito</value></data>
<data name="Tooltips.Settings.LogFileSize" xml:space="preserve"><value>Un file di log che raggiunge questa dimensione prosegue in un nuovo file numerato</value></data>
<data name="Tooltips.Settings.LogLevel" xml:space="preserve"><value>Livello minimo scritto nei file di log; Debug e Trace aiutano a trovare i problemi ma riempiono i file in fretta</value></data>
<data name="Tooltips.Settings.LogsFolder" xml:space="preserve"><value>File di log giornalieri, conservati per 14 giorni</value></data>
<data name="Tooltips.Settings.LogsTotal" xml:space="preserve"><value>Quando i file di log insieme superano questa dimensione, i più vecchi vengono eliminati, mai quello in scrittura</value></data>
<data name="Tooltips.Settings.Memory" xml:space="preserve"><value>I fotogrammi restano in memoria fino a questo limite, poi passano nella cartella della cache</value></data>
<data name="Tooltips.Settings.MemoryAuto" xml:space="preserve"><value>Auto: un quarto della memoria installata</value></data>
<data name="Tooltips.Settings.MemoryReset" xml:space="preserve"><value>Torna ad Auto: un quarto della memoria installata</value></data>
@@ -609,6 +614,7 @@
<data name="Tooltips.Settings.RestoreCancel" xml:space="preserve"><value>Tieni l'indice attuale al prossimo avvio</value></data>
<data name="Tooltips.Settings.RestoreConfirm" xml:space="preserve"><value>Al prossimo avvio di Chronos, salva una copia dell'indice attuale e poi ripristina questa copia</value></data>
<data name="Tooltips.Settings.RestorePending" xml:space="preserve"><value>La copia scelta sostituisce l'indice al prossimo avvio di Chronos</value></data>
<data name="Tooltips.Settings.Rotation" xml:space="preserve"><value>Inizia un nuovo file di log ogni giorno o ogni ora (UTC)</value></data>
<data name="Tooltips.Settings.Search" xml:space="preserve"><value>Trova un'impostazione per nome</value></data>
<data name="Tooltips.Settings.SelfTest" xml:space="preserve"><value>Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto</value></data>
<data name="Tooltips.Settings.SelfTestResult" xml:space="preserve"><value>Velocità sulla clip di prova sintetica 1280×720</value></data>
+9
View File
@@ -77,6 +77,7 @@ public partial class App : Application
}
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
ApplyLogSettings();
UiLanguage.Apply(Settings.Language);
ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
AppResources.Merge(this);
@@ -192,6 +193,14 @@ public partial class App : Application
{
Log.Warning("app", "Settings not saved", ex);
}
// Every settings change passes here, Settings › Advanced › Logs, its Reset and an imported file included.
ApplyLogSettings();
}
/// <summary>Settings › Advanced › Logs to the log files, from the next line on (owner review 2, R11).</summary>
private void ApplyLogSettings()
{
if (_log is not null) AppLogging.Apply(_log, Settings);
}
protected override void OnExit(ExitEventArgs e)
@@ -0,0 +1,38 @@
using Chronos.Core.Diagnostics;
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.
/// </summary>
public static class AppLogging
{
public const int DefaultDiagnosticsLogMb = (int)(DiagnosticsArchive.DefaultLogTailBytes / LogFileOptions.BytesPerMb);
public const int MaxRetentionDays = 3650;
public const int MaxFileMb = 10 * 1024;
public const int MaxTotalMb = 1024 * 1024;
public const int MaxDiagnosticsLogMb = 1024;
public static LogFileOptions Options(AppSettings settings) => new()
{
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,
};
/// <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 settings to <paramref name="sink"/> and the engine, from the next line on.</summary>
public static void Apply(FileLogSink sink, AppSettings settings)
{
var options = Options(settings);
sink.Configure(options);
Log.MinimumLevel = options.Level;
}
}
@@ -3,6 +3,7 @@ using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Naming;
@@ -185,6 +186,25 @@ public sealed class AppSettings
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
public DateTimeOffset? JobsClearedAt { get; set; }
// ---- Advanced › Logs (owner review 2, R11; applied by AppLogging) ----
/// <summary>Least severe level written to the log files.</summary>
public LogLevel LogLevel { get; set; } = LogLevel.Info;
/// <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>MB kept from the end of each log file in the diagnostics bundle.</summary>
public int DiagnosticsLogMb { get; set; } = AppLogging.DefaultDiagnosticsLogMb;
public sealed class WindowPlacement
{
public double Left { get; set; }
@@ -14,7 +14,8 @@ namespace Chronos.App.Infrastructure;
/// <summary>
/// The diagnostics bundle of Settings › Advanced (BRIEF §12.8, §12.9, §22 Phase 8): an environment report, the codec
/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose.
/// and encoder inventory, the settings, the latest failed jobs and the end of each log file (Settings › Advanced ›
/// Diagnostics logs), zipped into a folder the user chose.
/// Everything passes through <see cref="SecretScrubber"/> (the saved server token, passwords and keys never leave the
/// PC) and no photo or archive file is ever included.
/// </summary>
@@ -31,6 +32,7 @@ public static class DiagnosticsBundle
public static Task<string> CreateAsync(AppServices services, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default)
{
var settings = services.Settings.ToJson();
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
return Task.Run(async () =>
{
@@ -47,7 +49,7 @@ public static class DiagnosticsBundle
bundle.AddText("codecs.txt", codecs);
bundle.AddJson("settings.json", settings);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
bundle.AddLogs(services.Environment.LogDirectory, tailBytes: tailBytes, cancellationToken: ct);
}
File.Move(temp, path);
return path;
@@ -617,6 +617,31 @@
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding OpenLogsCommand}" ToolTip="{l:Loc Tooltips.Common.OpenLogs}" Margin="10,0,0,0" />
</Grid>
</HeaderedContentControl>
<!-- Owner review 2, R11: what the log files keep; a choice applies to them at once. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.LogLevel}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.Levels}" SelectedItem="{Binding Logs.SelectedLevel}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.LogLevel}" AutomationProperties.Name="{l:Loc Settings.Advanced.LogLevel}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.KeepLogs}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.RetentionChoices}" SelectedItem="{Binding Logs.SelectedRetention}"
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.KeepLogs}" AutomationProperties.Name="{l:Loc Settings.Advanced.KeepLogs}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.FileSize}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.FileSizeChoices}" SelectedItem="{Binding Logs.SelectedFileSize}"
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.LogFileSize}" AutomationProperties.Name="{l:Loc Settings.Advanced.FileSize}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.LogsTotal}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.TotalSizeChoices}" SelectedItem="{Binding Logs.SelectedTotalSize}"
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.LogsTotal}" AutomationProperties.Name="{l:Loc Settings.Advanced.LogsTotal}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Rotation}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.Rotations}" SelectedItem="{Binding Logs.SelectedRotation}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.Rotation}" AutomationProperties.Name="{l:Loc Settings.Advanced.Rotation}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.DiagnosticsLogs}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.DiagnosticsChoices}" SelectedItem="{Binding Logs.SelectedDiagnostics}"
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.DiagnosticsLogs}" AutomationProperties.Name="{l:Loc Settings.Advanced.DiagnosticsLogs}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Diagnostics}">
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.ExportBundle}" Command="{Binding ExportDiagnosticsCommand}" ToolTip="{l:Loc Tooltips.Settings.Diagnostics}"
ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" />
+21 -7
View File
@@ -30,8 +30,8 @@ namespace Chronos.App.Sections;
/// Archive rows show and change the open archive's own settings (archive.json, through the archive engine) and are the
/// defaults of new archives; Import and Analysis feed the defaults of new cards and the analysis jobs; Rendering feeds
/// the jobs from the next one on; Formats lists the decode tier per format on this PC with the codec extensions to
/// install; Advanced restores the index from a daily backup at the next start; About, the last page, shows this copy
/// (<see cref="ShellViewModel.About"/>, whose update notice Updates shows).
/// install; Advanced sets the log files (<see cref="Logs"/>) and restores the index from a daily backup at the next start;
/// About, the last page, shows this copy (<see cref="ShellViewModel.About"/>, whose update notice Updates shows).
/// </summary>
public sealed class SettingsViewModel : SectionViewModel
{
@@ -83,8 +83,9 @@ public sealed class SettingsViewModel : SectionViewModel
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.Diagnostics", "Settings.Advanced.Backup",
"Settings.Advanced.Restore", "Settings.Advanced.Reset"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
"Settings.Advanced.DiagnosticsLogs", "Settings.Advanced.Backup", "Settings.Advanced.Restore", "Settings.Advanced.Reset"]),
// The translation row shows outside English only, and the language changes while Settings is open.
new(SettingsPage.About, () => ["Shell.AppName", "About.Build", "About.Runtime", "About.System", "About.Licence", "About.ThirdParty",
.. Shell.About.IsTranslated ? (string[])["About.Translation"] : []]),
@@ -156,6 +157,10 @@ public sealed class SettingsViewModel : SectionViewModel
}, () => Loc.L("Tooltips.Settings.Parallelism"));
JobPriorities = [.. PriorityKinds.Select(k => new JobPriorityRow(k, kind => Shell.Services.PriorityQueue.LevelOf(kind), SetJobPriority))];
// ---- Advanced ----
// Saving applies them to the log files (App.SaveSettings).
Logs = new LogSettingsRows(_s, Save);
// ---- Storage ----
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
{
@@ -765,6 +770,10 @@ public sealed class SettingsViewModel : SectionViewModel
public string DataFolder => Shell.Services.Environment.DataDirectory;
public string LogsFolder => Shell.Services.Environment.LogDirectory;
public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff");
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
public LogSettingsRows Logs { get; }
public ICommand OpenDataFolderCommand { get; }
public ICommand OpenLogsCommand { get; }
public ICommand ExportDiagnosticsCommand { get; }
@@ -807,10 +816,10 @@ public sealed class SettingsViewModel : SectionViewModel
public ICommand ResetSectionCommand { get; }
/// <summary>
/// Advanced holds no setting with a default (paths and actions only), Formats only shows this PC and About only this
/// copy: they have no Reset section.
/// Formats only shows this PC and About only this copy: they have no Reset section. Advanced's resets its log rows
/// (owner review 2, R11); its paths and actions have no default.
/// </summary>
public bool CanResetSection => _page is not (SettingsPage.Advanced or SettingsPage.Formats or SettingsPage.About);
public bool CanResetSection => _page is not (SettingsPage.Formats or SettingsPage.About);
public ICommand ExportSettingsCommand { get; }
public ICommand ImportSettingsCommand { get; }
@@ -1494,6 +1503,9 @@ public sealed class SettingsViewModel : SectionViewModel
case SettingsPage.Updates:
_s.CheckForUpdates = defaults.CheckForUpdates;
break;
case SettingsPage.Advanced:
Logs.Reset();
break;
}
Save();
OnAllPropertiesChanged();
@@ -1599,6 +1611,7 @@ public sealed class SettingsViewModel : SectionViewModel
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
_interfacePriority?.Update();
foreach (var row in JobPriorities) row.Refresh();
Logs.Refresh();
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
@@ -1673,6 +1686,7 @@ public sealed class SettingsViewModel : SectionViewModel
foreach (var row in JobPriorities) row.Refresh();
foreach (var row in Formats) row.Refresh();
foreach (var row in MissingExtensions) row.Refresh();
Logs.Refresh();
ArchiveRoot.Refresh();
FolderTemplate.Refresh();
FileTemplate.Refresh();
+107
View File
@@ -0,0 +1,107 @@
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Ui.Mvvm;
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.
/// </summary>
public sealed class LogSettingsRows(AppSettings settings, Action save) : ObservableObject
{
public static readonly int[] RetentionPresets = [1, 3, 7, 14, 30, 90, 365];
public static readonly int[] FileSizePresets = [10, 20, 50, 100, 200, 500];
public static readonly int[] TotalSizePresets = [256, 512, 1024, 2048, 5120, 10240];
public static readonly int[] DiagnosticsPresets = [1, 2, 4, 8, 16, 32];
public IReadOnlyList<SettingsOption<LogLevel>> Levels =>
[.. Enum.GetValues<LogLevel>().Select(l => new SettingsOption<LogLevel>(l, Loc.L("Settings.Advanced.Level." + l)))];
public SettingsOption<LogLevel> SelectedLevel
{
get => Levels.FirstOrDefault(l => l.Value == settings.LogLevel) ?? Levels.First(l => l.Value == LogLevel.Info);
set => Store(value, settings.LogLevel, v => settings.LogLevel = v);
}
public IReadOnlyList<SettingsOption<int>> RetentionChoices =>
[.. With(RetentionPresets, settings.LogRetentionDays).Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Advanced.Days", n)))];
public SettingsOption<int> SelectedRetention
{
get => RetentionChoices.First(c => c.Value == settings.LogRetentionDays);
set => Store(value, settings.LogRetentionDays, v => settings.LogRetentionDays = v);
}
public IReadOnlyList<SettingsOption<int>> FileSizeChoices => Sizes(FileSizePresets, settings.LogMaxFileMb);
public SettingsOption<int> SelectedFileSize
{
get => FileSizeChoices.First(c => c.Value == settings.LogMaxFileMb);
set => Store(value, settings.LogMaxFileMb, v => settings.LogMaxFileMb = v);
}
public IReadOnlyList<SettingsOption<int>> TotalSizeChoices => Sizes(TotalSizePresets, settings.LogMaxTotalMb);
public SettingsOption<int> SelectedTotalSize
{
get => TotalSizeChoices.First(c => c.Value == settings.LogMaxTotalMb);
set => Store(value, settings.LogMaxTotalMb, v => settings.LogMaxTotalMb = v);
}
public IReadOnlyList<SettingsOption<LogRotation>> Rotations =>
[.. Enum.GetValues<LogRotation>().Select(r => new SettingsOption<LogRotation>(r, Loc.L("Settings.Advanced.Rotation." + r)))];
public SettingsOption<LogRotation> SelectedRotation
{
get => Rotations.FirstOrDefault(r => r.Value == settings.LogRotation) ?? Rotations[0];
set => Store(value, settings.LogRotation, v => settings.LogRotation = v);
}
public IReadOnlyList<SettingsOption<int>> DiagnosticsChoices =>
[.. With(DiagnosticsPresets, settings.DiagnosticsLogMb).Select(n => new SettingsOption<int>(n, Megabytes(n)))];
public SettingsOption<int> SelectedDiagnostics
{
get => DiagnosticsChoices.First(c => c.Value == settings.DiagnosticsLogMb);
set => Store(value, settings.DiagnosticsLogMb, v => settings.DiagnosticsLogMb = v);
}
/// <summary>The defaults of every row (Reset section on Advanced); the caller saves.</summary>
public void Reset()
{
var defaults = new AppSettings();
settings.LogLevel = defaults.LogLevel;
settings.LogRetentionDays = defaults.LogRetentionDays;
settings.LogMaxFileMb = defaults.LogMaxFileMb;
settings.LogMaxTotalMb = defaults.LogMaxTotalMb;
settings.LogRotation = defaults.LogRotation;
settings.DiagnosticsLogMb = defaults.DiagnosticsLogMb;
Refresh();
}
/// <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)
{
if (choice is null || EqualityComparer<T>.Default.Equals(choice.Value, current)) return;
set(choice.Value);
save();
OnPropertyChanged(property);
}
/// <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) =>
[
.. With(presets, current).Where(n => n > 0).Select(n => new SettingsOption<int>(n, Megabytes(n))),
new(0, Loc.L("Settings.Advanced.NoLimit")),
];
private static IEnumerable<int> With(int[] presets, int current) => (presets.Contains(current) ? presets : presets.Append(current)).Order();
private static string Megabytes(int n) => Loc.L("Common.Size.MB", Formatting.Count(n));
}
+254
View File
@@ -0,0 +1,254 @@
using System.Globalization;
using System.Text.RegularExpressions;
namespace Chronos.Core.Diagnostics;
/// <summary>How often a <see cref="FileLogSink"/> starts a new file (UTC).</summary>
public enum LogRotation
{
/// <summary>One file per day: <c>prefix-yyyyMMdd.log</c>.</summary>
Daily,
/// <summary>One file per hour: <c>prefix-yyyyMMdd-HH.log</c>.</summary>
Hourly,
}
/// <summary>
/// What a <see cref="FileLogSink"/> writes and keeps (owner review 2, R11): the least severe level written, the days files
/// are kept, the size at which a file continues in a numbered one, the size the sink's files may take together (0: no
/// limit for either size) and the rotation period. Sizes are in MB of 2²⁰ bytes, like the diagnostics tail.
/// </summary>
public sealed record LogFileOptions
{
public const int DefaultRetentionDays = 14;
public const int DefaultMaxFileMb = 50;
public const int DefaultMaxTotalMb = 1024;
/// <summary>Bytes in one MB of the limits.</summary>
public const long BytesPerMb = 1L << 20;
public LogLevel Level { get; init; } = LogLevel.Info;
/// <summary>Files last written longer ago are deleted; 0 or less keeps them whatever their age.</summary>
public int RetentionDays { get; init; } = DefaultRetentionDays;
/// <summary>A file this large continues in the next numbered file (<c>.1.log</c>, <c>.2.log</c>…); 0 = no limit.</summary>
public int MaxFileMb { get; init; } = DefaultMaxFileMb;
/// <summary>While the sink's files together are larger, the oldest are deleted (never the one being written); 0 = no limit.</summary>
public int MaxTotalMb { get; init; } = DefaultMaxTotalMb;
public LogRotation Rotation { get; init; } = LogRotation.Daily;
}
/// <summary>
/// Appends log lines to rotating files: <c>prefix-yyyyMMdd.log</c> (daily) or <c>prefix-yyyyMMdd-HH.log</c> (hourly, UTC);
/// a file that reaches <see cref="LogFileOptions.MaxFileMb"/> continues in <c>prefix-yyyyMMdd[-HH].1.log</c>, <c>.2</c>…
/// At every new file (and when the options change) files older than the retention are deleted, then the oldest while
/// the sink's files exceed <see cref="LogFileOptions.MaxTotalMb"/>; only names this sink writes are touched, never the
/// file being written. Lines are flushed one by one; <see cref="Configure"/> applies new options from the next line.
/// </summary>
public sealed class FileLogSink : ILogSink, IDisposable
{
private readonly string _directory;
private readonly string _prefix;
private readonly TimeProvider _time;
private readonly Regex _ownName;
private readonly Lock _gate = new();
private LogFileOptions _options;
private FileStream? _stream;
private StreamWriter? _writer;
private string? _stem;
private int _part;
private string? _path;
private bool _disposed;
/// <summary>Daily files kept for <paramref name="retainDays"/>, with the default size limits.</summary>
public FileLogSink(string directory, string prefix, int retainDays = LogFileOptions.DefaultRetentionDays)
: this(directory, prefix, new LogFileOptions { RetentionDays = retainDays })
{
}
public FileLogSink(string directory, string prefix, LogFileOptions options, TimeProvider? time = null)
{
ArgumentNullException.ThrowIfNull(options);
_directory = Path.GetFullPath(directory);
_prefix = prefix;
_options = options;
_time = time ?? TimeProvider.System;
_ownName = new Regex("^" + Regex.Escape(prefix) + @"-\d{8}(-\d{2})?(\.\d+)?\.log$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
Directory.CreateDirectory(_directory);
}
public LogFileOptions Options
{
get
{
lock (_gate) return _options;
}
}
/// <summary>The file being written; before the first line, the one it will go to.</summary>
public string CurrentPath
{
get
{
lock (_gate) return _path ?? PathOf(Stem(Now), 0);
}
}
private DateTime Now => _time.GetUtcNow().UtcDateTime;
public void Write(LogLevel level, string category, string message, Exception? exception)
{
lock (_gate)
{
if (_disposed || level < _options.Level) return;
var now = Now;
EnsureFile(now);
_writer!.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{now:O} {level,-7} {category}: {message}"));
if (exception is not null) _writer.WriteLine(exception.ToString());
}
}
/// <summary>New options from the next line on; a change of retention or limits prunes at once.</summary>
public void Configure(LogFileOptions options)
{
ArgumentNullException.ThrowIfNull(options);
lock (_gate)
{
var prune = options.RetentionDays != _options.RetentionDays || options.MaxTotalMb != _options.MaxTotalMb;
_options = options;
if (prune) Prune(Now);
}
}
/// <summary>Deletes the files older than the retention, then the oldest while the total exceeds the limit.</summary>
public void PruneNow()
{
lock (_gate) Prune(Now);
}
public void Dispose()
{
lock (_gate)
{
_disposed = true;
Close();
}
}
/// <summary>Opens the file of this period, or the next part when the current one is full, and prunes when it changes.</summary>
private void EnsureFile(DateTime now)
{
var stem = Stem(now);
var newPeriod = _writer is null || stem != _stem;
if (!newPeriod && !IsFull) return;
Close();
if (newPeriod)
{
// A restart continues the newest file of the period.
_stem = stem;
_part = LastPart(stem);
}
else
{
_part++;
}
Open();
if (IsFull)
{
Close();
_part++;
Open();
}
Prune(now);
}
private bool IsFull => _options.MaxFileMb > 0 && _stream is { } stream && stream.Position >= _options.MaxFileMb * LogFileOptions.BytesPerMb;
private void Open()
{
_path = PathOf(_stem!, _part);
_stream = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
_writer = new StreamWriter(_stream) { AutoFlush = true };
}
private void Close()
{
_writer?.Dispose();
_writer = null;
_stream = null;
}
private string Stem(DateTime now) => _options.Rotation == LogRotation.Hourly
? string.Create(CultureInfo.InvariantCulture, $"{_prefix}-{now:yyyyMMdd-HH}")
: string.Create(CultureInfo.InvariantCulture, $"{_prefix}-{now:yyyyMMdd}");
private string PathOf(string stem, int part) =>
Path.Combine(_directory, part == 0 ? stem + ".log" : string.Create(CultureInfo.InvariantCulture, $"{stem}.{part}.log"));
/// <summary>The highest part of <paramref name="stem"/> on disk (0 when there is none).</summary>
private int LastPart(string stem)
{
var last = 0;
try
{
foreach (var file in Directory.EnumerateFiles(_directory, stem + ".*.log"))
{
var name = Path.GetFileName(file);
if (name.Length <= stem.Length + 5 || !name.StartsWith(stem + ".", StringComparison.OrdinalIgnoreCase)) continue;
if (int.TryParse(name[(stem.Length + 1)..^4], NumberStyles.None, CultureInfo.InvariantCulture, out var part)) last = int.Max(last, part);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
return last;
}
private void Prune(DateTime now)
{
List<FileInfo> files;
try
{
files = [.. new DirectoryInfo(_directory).EnumerateFiles(_prefix + "-*.log").Where(f => _ownName.IsMatch(f.Name))];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return;
}
var kept = new List<FileInfo>();
var cutoff = _options.RetentionDays > 0 ? now.AddDays(-_options.RetentionDays) : DateTime.MinValue;
foreach (var file in files)
{
if (!IsCurrent(file) && file.LastWriteTimeUtc < cutoff && TryDelete(file)) continue;
kept.Add(file);
}
if (_options.MaxTotalMb <= 0) return;
var limit = _options.MaxTotalMb * LogFileOptions.BytesPerMb;
// The directory may report a stale size for the file still open: its stream knows.
var total = kept.Sum(f => IsCurrent(f) && _stream is { } stream ? stream.Length : f.Length);
foreach (var file in kept.Where(f => !IsCurrent(f)).OrderBy(f => f.LastWriteTimeUtc).ThenBy(f => f.Name, StringComparer.Ordinal))
{
if (total <= limit) break;
var length = file.Length;
if (TryDelete(file)) total -= length;
}
}
private bool IsCurrent(FileInfo file) => _path is not null && string.Equals(file.FullName, _path, StringComparison.OrdinalIgnoreCase);
private static bool TryDelete(FileInfo file)
{
try
{
file.Delete();
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}
}
+5 -61
View File
@@ -17,7 +17,11 @@ public interface ILogSink
void Write(LogLevel level, string category, string message, Exception? exception);
}
/// <summary>Tiny engine-wide logger. Core code logs through it; hosts plug in a sink.</summary>
/// <summary>
/// Tiny engine-wide logger. Core code logs through it; hosts plug in a sink. <see cref="MinimumLevel"/> drops lines no sink
/// wants before they are formatted: hosts set it to the lowest level of their sinks, which each keep their own (a
/// <see cref="FileLogSink"/> its <see cref="LogFileOptions.Level"/>, the server's console and files their filters).
/// </summary>
public static class Log
{
private static ILogSink _sink = new ConsoleSink();
@@ -55,66 +59,6 @@ public static class Log
}
}
/// <summary>Appends log lines to rotating files (one per day, kept for <c>retainDays</c>).</summary>
public sealed class FileLogSink : ILogSink, IDisposable
{
private readonly string _directory;
private readonly string _prefix;
private readonly int _retainDays;
private readonly Lock _gate = new();
private StreamWriter? _writer;
private DateOnly _day;
public FileLogSink(string directory, string prefix, int retainDays = 14)
{
_directory = directory;
_prefix = prefix;
_retainDays = retainDays;
Directory.CreateDirectory(directory);
}
public string CurrentPath => Path.Combine(_directory, $"{_prefix}-{_day:yyyyMMdd}.log");
public void Write(LogLevel level, string category, string message, Exception? exception)
{
lock (_gate)
{
var today = DateOnly.FromDateTime(DateTime.UtcNow);
if (_writer is null || today != _day)
{
_writer?.Dispose();
_day = today;
_writer = new StreamWriter(new FileStream(CurrentPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { AutoFlush = true };
Prune();
}
_writer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:O} {level,-7} {category}: {message}"));
if (exception is not null) _writer.WriteLine(exception.ToString());
}
}
private void Prune()
{
foreach (var file in Directory.EnumerateFiles(_directory, _prefix + "-*.log"))
{
if (File.GetLastWriteTimeUtc(file) < DateTime.UtcNow.AddDays(-_retainDays))
{
try
{
File.Delete(file);
}
catch (IOException)
{
}
}
}
}
public void Dispose()
{
lock (_gate) _writer?.Dispose();
}
}
/// <summary>Writes every event to several sinks.</summary>
public sealed class TeeLogSink(params ILogSink[] sinks) : ILogSink
{
+22 -1
View File
@@ -6,7 +6,8 @@ namespace Chronos.Protocol;
/// that saved values (ports, TLS, chunk size, job history) wait for a restart. <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).
/// <see cref="Parallelism"/> is how many photos the running job processes at once (jobs run one at a time), and
/// <see cref="PriorityQueue"/> with <see cref="JobPriorities"/> the priority queue (owner review 1); both apply at once.
/// <see cref="PriorityQueue"/> with <see cref="JobPriorities"/> the priority queue (owner review 1); both apply at once, as
/// do <see cref="Logs"/> (owner review 2, R11; a request without them keeps them as they are).
/// </summary>
public sealed record ServerSettingsDto(
string ServerName,
@@ -25,10 +26,30 @@ public sealed record ServerSettingsDto(
int JobHistoryDays,
int TokenLifetimeDays,
int UploadRetentionHours,
LogSettingsDto Logs,
IReadOnlyList<string> Locked,
bool RestartRequired,
bool ProxyWarning);
/// <summary>
/// The log settings of <see cref="ServerSettingsDto"/> (owner review 2, R11): the least severe level of the files and of the
/// console (<c>trace</c>, <c>debug</c>, <c>information</c>, <c>warning</c>, <c>error</c>, <c>critical</c>, <c>none</c>), the
/// days log files are kept, the size at which a file continues in a numbered one and the size of all of them (MB of 2²⁰
/// bytes, 0 = no limit), the rotation (<c>daily</c> or <c>hourly</c>, UTC), the days audit entries are kept (0 = forever)
/// and the MB of the end of each log file in the diagnostics zip. Their locks use the server.json names (<c>LogLevel</c>,
/// <c>ConsoleLogLevel</c>, <c>LogRetentionDays</c>, <c>LogMaxFileMb</c>, <c>LogMaxTotalMb</c>, <c>LogRotation</c>,
/// <c>AuditRetentionDays</c>, <c>DiagnosticsLogMb</c>).
/// </summary>
public sealed record LogSettingsDto(
string FileLevel,
string ConsoleLevel,
int RetentionDays,
int MaxFileMb,
int MaxTotalMb,
string Rotation,
int AuditRetentionDays,
int DiagnosticsLogMb);
/// <summary>A kind of job (<c>render</c>) and its level in the server's priority queue: <c>high</c>, <c>normal</c> or <c>low</c>.</summary>
public sealed record JobPriorityDto(string Kind, string Level);
+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;
}
}
@@ -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);