Files
Chronos/src/Chronos.Core/Diagnostics/FileLogSink.cs
T
Alby96 e384564784 fix: logging never fails a job, one backup retention, first copy after the upgrade
Owner review 2, phase 2 review findings (scheduler core).

- Log.Write caught only IOException. Microsoft.Extensions.Logging wraps
  provider failures in an AggregateException, so a log line that could not
  be written (in tests: the process-wide sink of a stopped server whose log
  folder was gone) escaped JobEngine.RunAsync's catch before the failure was
  stored: the job stayed running and the worker faulted. This was the cause
  of the intermittent JobApiTests/ArchiveModuleTests failures. Log.Write now
  drops any non-fatal sink failure, TeeLogSink keeps a line from the other
  sinks, FileLogSink drops a line it cannot write and reopens the file at the
  next one, and LoggerSink drops what the providers throw. The scheduler's
  loop relies on the same guarantee.
- The daily backup loop (RunDailyAsync, IsDue, Interval, CheckInterval) had
  no caller since the index-backup schedule replaced it; it is removed and
  the DatabaseBackups summary describes the schedule.
- The first copy after the upgrade no longer waits a day (or for 03:00):
  SystemSchedule.LastDone seeds a new row due at once when its work was last
  done a period or more before, and both hosts pass the newest copy in the
  backups folder for index-backup.
- Back up now (Settings and Archive), the copy kept before a restore and a
  backup job that keeps fewer prune to the largest Copies kept of the backup
  schedules (DatabaseBackups.KeptAsync), not a fixed three. The four
  tooltips that promised three daily copies are reworded (en, it) and their
  stale translations deleted.
- New tests for the scheduler loop itself: a tick, Wake, a pass that threw,
  and dispose during a pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c5ad0c4c3f636129afe5dd1ce039185516da5621)
2026-10-27 09:56:47 +01:00

279 lines
10 KiB
C#

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>
/// Whether a total of <paramref name="maxTotalMb"/> is below one file of <paramref name="maxFileMb"/>: each finished file
/// would be deleted as soon as the next one opens. The server refuses such settings; the desktop raises the total.
/// </summary>
public static bool TotalBelowFile(int maxFileMb, int maxTotalMb) => maxTotalMb > 0 && maxFileMb > maxTotalMb;
}
/// <summary>
/// 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; one that cannot be written (the folder removed, a full disk) is dropped
/// and the next opens the file again. <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;
try
{
EnsureFile(now);
_writer!.WriteLine(string.Create(CultureInfo.InvariantCulture, $"{now:O} {level,-7} {category}: {message}"));
if (exception is not null) _writer.WriteLine(exception.ToString());
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The folder is gone, the disk is full or the file is locked: the line is dropped and the next one opens
// the file again.
Close();
}
}
}
/// <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()
{
var writer = _writer;
_writer = null;
_stream = null;
try
{
writer?.Dispose();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// What it still held could not be flushed (a full disk); its file is closed all the same.
}
}
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;
}
}
}