1

是否可以检查是否有任何错误已记录到ILoggerSerilog 中?

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

SomeAlgorithm(log);

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

1 回答 1

4

只需几行代码,自定义接收器就可以做到这一点。

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) { ...
于 2015-04-29T22:18:03.867 回答