Files
Febe/src/Febe.App/FebeLog.cs
T

262 lines
9.3 KiB
C#

using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
using Microsoft.Extensions.Logging;
namespace Febe.App;
/// <summary>
/// The log of Febe, the same in both shells (spec §8.2, §13.2): one file per local day in <c>Dati/registro</c>
/// (<c>febe-AAAA-MM-GG.log</c>), kept fourteen days, at most 20 MB a day, and the same lines on the console, if any
/// (<c>docker logs</c>). Only actions and outcomes: every message passes through <see cref="Scrub"/>, which removes
/// addresses (signed CDN addresses, tokens); exceptions are written as type and first line only. Passwords, cookies,
/// keys and response bodies never reach this class.
/// </summary>
public sealed partial class FebeLog : IDisposable
{
public const int DefaultKeepDays = 14;
public const long DefaultMaxBytesPerDay = 20L * 1024 * 1024;
private const string Prefix = "febe-";
private const string Extension = ".log";
private readonly Lock _gate = new();
private readonly string? _folder;
private readonly TextWriter? _console;
private readonly IClock _clock;
private readonly int _keepDays;
private readonly long _maxBytesPerDay;
private StreamWriter? _file;
private DateOnly _day;
private long _written;
private bool _capped;
private bool _disposed;
/// <param name="folder">Dati/registro; null writes to the console only (configuration problems, tests).</param>
/// <param name="console">Console writer; null for none.</param>
/// <param name="clock">Time of the lines and of the daily file.</param>
/// <param name="keepDays">Days of files kept.</param>
/// <param name="maxBytesPerDay">Above this the day's file stops growing (the console still gets the lines).</param>
public FebeLog(string? folder, TextWriter? console, IClock clock, int keepDays = DefaultKeepDays, long maxBytesPerDay = DefaultMaxBytesPerDay)
{
_folder = folder is null ? null : Path.GetFullPath(folder);
_console = console;
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_keepDays = Math.Max(1, keepDays);
_maxBytesPerDay = maxBytesPerDay;
}
/// <summary>Lowest level written to the console; the file gets everything from Information up.</summary>
public LogLevel ConsoleLevel { get; init; } = LogLevel.Information;
/// <summary>The log folder, when there is one.</summary>
public string? Folder => _folder;
public void Info(string source, string message) => Write(LogLevel.Information, source, message);
public void Warn(string source, string message, Exception? exception = null) => Write(LogLevel.Warning, source, message, exception);
public void Error(string source, string message, Exception? exception = null) => Write(LogLevel.Error, source, message, exception);
/// <summary>Writes one line. Never throws: a log that cannot be written must not stop Febe.</summary>
public void Write(LogLevel level, string source, string message, Exception? exception = null)
{
if (level < LogLevel.Information)
{
return;
}
var now = _clock.Now;
var local = TimeZoneInfo.ConvertTime(now, _clock.LocalZone);
var text = Scrub(message);
if (exception is not null)
{
text += $" ({exception.GetType().Name}: {Scrub(FirstLine(exception.Message))})";
}
var line = string.Create(CultureInfo.InvariantCulture, $"{local:yyyy-MM-dd HH:mm:ss.fff zzz} {Label(level)} [{source}] {text}");
lock (_gate)
{
if (_disposed)
{
return;
}
if (_console is not null && level >= ConsoleLevel)
{
try
{
_console.WriteLine(line);
}
catch (IOException)
{
}
}
WriteFileLocked(DateOnly.FromDateTime(local.DateTime), line);
}
}
/// <summary>The adapter for the browser layer (it logs only CDP command names, states and counts).</summary>
public IBrowserLog ForBrowser() => new DelegateBrowserLog((level, message, exception) => Write(
level switch
{
BrowserLogLevel.Error => LogLevel.Error,
BrowserLogLevel.Warning => LogLevel.Warning,
BrowserLogLevel.Information => LogLevel.Information,
_ => LogLevel.Debug,
},
"browser",
message,
exception));
/// <summary>The adapter for ASP.NET Core (warnings and errors only; messages scrubbed like every other line).</summary>
public ILoggerProvider ForAspNet() => new Provider(this);
public void Dispose()
{
lock (_gate)
{
_disposed = true;
_file?.Dispose();
_file = null;
}
}
/// <summary>Removes addresses (anything like <c>scheme://…</c>) and line breaks from a message.</summary>
public static string Scrub(string? message)
{
if (string.IsNullOrEmpty(message))
{
return string.Empty;
}
var clean = Addresses().Replace(message, "<indirizzo>");
return clean.Replace('\r', ' ').Replace('\n', ' ');
}
/// <summary>Log files older than <paramref name="keepDays"/> days (today included) are removed; only <c>febe-*.log</c>.</summary>
public static IReadOnlyList<string> ApplyRetention(string folder, DateOnly today, int keepDays)
{
var removed = new List<string>();
if (!Directory.Exists(folder))
{
return removed;
}
var oldestKept = today.AddDays(-(Math.Max(1, keepDays) - 1));
foreach (var file in Directory.EnumerateFiles(folder, Prefix + "*" + Extension))
{
var name = Path.GetFileNameWithoutExtension(file);
if (DateOnly.TryParseExact(name[Prefix.Length..], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) && day < oldestKept)
{
try
{
File.Delete(file);
removed.Add(file);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
}
return removed;
}
public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension;
private void WriteFileLocked(DateOnly day, string line)
{
if (_folder is null)
{
return;
}
try
{
if (_file is null || day != _day)
{
_file?.Dispose();
_file = null;
Directory.CreateDirectory(_folder);
ApplyRetention(_folder, day, _keepDays);
var path = Path.Combine(_folder, FileNameFor(day));
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
_written = stream.Length;
_file = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
_day = day;
_capped = false;
}
if (_capped)
{
return;
}
if (_written + line.Length + 1 > _maxBytesPerDay)
{
_file.WriteLine("Registro di oggi troppo lungo: le righe successive vanno solo sulla console.");
_capped = true;
return;
}
_file.WriteLine(line);
_written += Encoding.UTF8.GetByteCount(line) + 1;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The disk is full or the folder went away: the console still has the line.
_file?.Dispose();
_file = null;
}
}
private static string Label(LogLevel level) => level switch
{
LogLevel.Critical or LogLevel.Error => "ERRORE ",
LogLevel.Warning => "AVVISO ",
_ => "INFO ",
};
private static string FirstLine(string text)
{
var line = text.Split('\n')[0].Trim();
return line.Length > 300 ? line[..300] : line;
}
[GeneratedRegex(@"\b[a-zA-Z][a-zA-Z0-9+.-]*://\S+", RegexOptions.CultureInvariant)]
private static partial Regex Addresses();
private sealed class Provider(FebeLog log) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => new Logger(log, categoryName);
public void Dispose()
{
}
}
private sealed class Logger(FebeLog log, string category) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
var source = category.StartsWith("Febe.", StringComparison.Ordinal) ? "web" : "aspnet";
log.Write(logLevel, source, formatter(state, exception), exception);
}
}
}