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; /// /// The log of Febe, the same in both shells (spec §8.2, §13.2): one file per local day in Dati/registro /// (febe-AAAA-MM-GG.log), kept fourteen days, at most 20 MB a day, and the same lines on the console, if any /// (docker logs). Only actions and outcomes: every message passes through , 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. /// 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; /// Dati/registro; null writes to the console only (configuration problems, tests). /// Console writer; null for none. /// Time of the lines and of the daily file. /// Days of files kept. /// Above this the day's file stops growing (the console still gets the lines). 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; } /// Lowest level written to the console; the file gets everything from Information up. public LogLevel ConsoleLevel { get; init; } = LogLevel.Information; /// The log folder, when there is one. 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); /// Writes one line. Never throws: a log that cannot be written must not stop Febe. 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); } } /// The adapter for the browser layer (it logs only CDP command names, states and counts). /// The category of the lines (the remote view writes as «vista»). public IBrowserLog ForBrowser(string category = "browser") => new DelegateBrowserLog((level, message, exception) => Write( level switch { BrowserLogLevel.Error => LogLevel.Error, BrowserLogLevel.Warning => LogLevel.Warning, BrowserLogLevel.Information => LogLevel.Information, _ => LogLevel.Debug, }, category, message, exception)); /// The adapter for ASP.NET Core (warnings and errors only; messages scrubbed like every other line). public ILoggerProvider ForAspNet() => new Provider(this); public void Dispose() { lock (_gate) { _disposed = true; _file?.Dispose(); _file = null; } } /// Removes addresses (anything like scheme://…) and line breaks from a message. public static string Scrub(string? message) { if (string.IsNullOrEmpty(message)) { return string.Empty; } var clean = Addresses().Replace(message, ""); return clean.Replace('\r', ' ').Replace('\n', ' '); } /// Log files older than days (today included) are removed; only febe-*.log. public static IReadOnlyList ApplyRetention(string folder, DateOnly today, int keepDays) { var removed = new List(); 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 state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (!IsEnabled(logLevel)) { return; } var source = category.StartsWith("Febe.", StringComparison.Ordinal) ? "web" : "aspnet"; log.Write(logLevel, source, formatter(state, exception), exception); } } }