是否可以检查是否有任何错误已记录到 Serilog 中的“ILogger”?

Is it possible to check if any errors has been logged to a `ILogger` in Serilog?

是否可以检查是否有任何错误已记录到 Serilog 中的 ILogger

var log = new LoggerConfiguration().CreateLogger();

SomeAlgorithm(log);

// How can I check if an error was logged?

自定义接收器只需几行代码即可完成此操作。

class ErrorDetector : ILogEventSink {
    volatile bool _errorDetected;
    public bool ErrorDetected { get { return _errorDetected; } }
    public void Emit(LogEvent evt) {
        if (evt.Level == LogEventLevel.Error ||
            evt.Level == LogEventLevel.Fatal) {
            _errorDetected = true;
        }
    }
}

然后:

var detector = new ErrorDetector();
var log = new LoggerConfiguration()
    .WriteTo.Sink(detector)
    .CreateLogger();

// Later
if (detector.ErrorDetected) { ...