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:
1 parent
1f089888e8
commit
0e84392f4f
35 files changed
+1485
-119
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user