using Chronos.Core.Diagnostics; using Chronos.Testing; namespace Chronos.Core.Tests.Diagnostics; /// /// Logging never throws into the code that logs: the job engine and the scheduler log from their error handling, and a line /// that escaped there once left a failed job running and could stop a worker. Serial: these tests replace the process-wide sink. /// [Serial] public sealed class LogTests { /// Throws what Microsoft.Extensions.Logging throws when a file provider's folder is gone. private sealed class BrokenSink : ILogSink { public int Calls; public void Write(LogLevel level, string category, string message, Exception? exception) { Interlocked.Increment(ref Calls); throw new AggregateException("An error occurred while writing to logger(s).", new DirectoryNotFoundException("Could not find a part of the path")); } } private sealed class ListSink : ILogSink { public List Lines { get; } = []; public void Write(LogLevel level, string category, string message, Exception? exception) { lock (Lines) Lines.Add($"{level} {category}: {message}"); } } [Test] public void ALineASinkCannotWriteIsDroppedWithoutThrowing() { var sink = new BrokenSink(); var previous = Log.Sink; var level = Log.MinimumLevel; Log.SetSink(sink); Log.MinimumLevel = LogLevel.Debug; try { Log.Debug("test", "debug"); Log.Info("test", "info"); Log.Warning("test", "warning", new InvalidOperationException("cause")); Log.Error("test", "error", new InvalidOperationException("cause")); Log.Write(LogLevel.Error, "test", "write", null); } finally { Log.SetSink(previous); Log.MinimumLevel = level; } Assert.Equal(5, sink.Calls); } [Test] public void OneSinkOfATeeThatCannotWriteDoesNotKeepTheLineFromTheOthers() { var broken = new BrokenSink(); var kept = new ListSink(); var tee = new TeeLogSink(broken, kept); tee.Write(LogLevel.Warning, "test", "first", null); tee.Write(LogLevel.Error, "test", "second", new IOException("disk")); Assert.Equal(2, broken.Calls); Assert.SequenceEqual(["Warning test: first", "Error test: second"], kept.Lines); } }