using System.Collections.Concurrent; using System.Globalization; using System.Text; using System.Text.Json; using Anubis.Core; using Anubis.Diagnostics; namespace Anubis.Server; /// /// Structured logs (SPEC 2.2, issue #10): one JSON object per line on the console and in a daily file under /// data/logs, every text passed through the so no secret reaches a log. The last 14 files are kept. /// internal sealed class JsonLogProvider : ILoggerProvider { public const int KeepFiles = 14; private readonly string? _folder; private readonly IClock _clock; private readonly bool _console; private readonly Lock _gate = new(); private readonly ConcurrentDictionary _loggers = new(StringComparer.Ordinal); private StreamWriter? _file; private string? _fileDay; public JsonLogProvider(string? folder, IClock clock, bool console) { _folder = folder; _clock = clock; _console = console; } public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new JsonLogger(name, this)); internal void Write(string category, LogLevel level, EventId eventId, string message, Exception? exception) { LogCounter.Record(level); var now = _clock.UtcNow; using var buffer = new MemoryStream(); using (var json = new Utf8JsonWriter(buffer)) { json.WriteStartObject(); json.WriteString("at", now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture)); json.WriteString("level", level.ToString().ToLowerInvariant()); json.WriteString("category", category); if (eventId.Id != 0) { json.WriteNumber("event", eventId.Id); } json.WriteString("message", Redactor.Redact(message)); if (exception is not null) { json.WriteString("error", Redactor.Redact(exception.GetType().Name + ": " + exception.Message)); json.WriteString("stack", Redactor.Redact(exception.StackTrace)); } json.WriteEndObject(); } var line = Encoding.UTF8.GetString(buffer.ToArray()); lock (_gate) { if (_console) { Console.Out.WriteLine(line); } WriteFile(now, line); } } private void WriteFile(DateTimeOffset now, string line) { if (_folder is null) { return; } try { var day = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture); if (_file is null || _fileDay != day) { _file?.Dispose(); Directory.CreateDirectory(_folder); _file = new StreamWriter(new FileStream(Path.Combine(_folder, "anubis-" + day + ".log"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), new UTF8Encoding(false)) { AutoFlush = true, }; _fileDay = day; Prune(); } _file.WriteLine(line); } catch (IOException) { // A full or read-only disk must not stop the application: the console still has the line. } catch (UnauthorizedAccessException) { } } private void Prune() { foreach (var old in Directory.EnumerateFiles(_folder!, "anubis-*.log").OrderDescending(StringComparer.Ordinal).Skip(KeepFiles)) { File.Delete(old); } } public void Dispose() { lock (_gate) { _file?.Dispose(); _file = null; } } private sealed class JsonLogger(string category, JsonLogProvider provider) : ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { if (!IsEnabled(logLevel)) { return; } provider.Write(category, logLevel, eventId, formatter(state, exception), exception); } } }