using System.Globalization; using System.Text.RegularExpressions; namespace Chronos.Core.Diagnostics; /// How often a starts a new file (UTC). public enum LogRotation { /// One file per day: prefix-yyyyMMdd.log. Daily, /// One file per hour: prefix-yyyyMMdd-HH.log. Hourly, } /// /// What a 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. /// public sealed record LogFileOptions { public const int DefaultRetentionDays = 14; public const int DefaultMaxFileMb = 50; public const int DefaultMaxTotalMb = 1024; /// Bytes in one MB of the limits. public const long BytesPerMb = 1L << 20; public LogLevel Level { get; init; } = LogLevel.Info; /// Files last written longer ago are deleted; 0 or less keeps them whatever their age. public int RetentionDays { get; init; } = DefaultRetentionDays; /// A file this large continues in the next numbered file (.1.log, .2.log…); 0 = no limit. public int MaxFileMb { get; init; } = DefaultMaxFileMb; /// While the sink's files together are larger, the oldest are deleted (never the one being written); 0 = no limit. public int MaxTotalMb { get; init; } = DefaultMaxTotalMb; public LogRotation Rotation { get; init; } = LogRotation.Daily; /// /// Whether a total of is below one file of : each finished file /// would be deleted as soon as the next one opens. The server refuses such settings; the desktop raises the total. /// public static bool TotalBelowFile(int maxFileMb, int maxTotalMb) => maxTotalMb > 0 && maxFileMb > maxTotalMb; } /// /// Appends log lines to rotating files: prefix-yyyyMMdd.log (daily) or prefix-yyyyMMdd-HH.log (hourly, UTC); /// a file that reaches continues in prefix-yyyyMMdd[-HH].1.log, .2… /// 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 ; 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. applies new options from the next line. /// 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; /// Daily files kept for , with the default size limits. 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; } } /// The file being written; before the first line, the one it will go to. 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(); } } } /// New options from the next line on; a change of retention or limits prunes at once. 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); } } /// Deletes the files older than the retention, then the oldest while the total exceeds the limit. public void PruneNow() { lock (_gate) Prune(Now); } public void Dispose() { lock (_gate) { _disposed = true; Close(); } } /// Opens the file of this period, or the next part when the current one is full, and prunes when it changes. 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")); /// The highest part of on disk (0 when there is none). 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 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(); 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; } } }