A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/Microsoft/serilog-sinks-testcorrelator below:

MitchBodmer/serilog-sinks-testcorrelator: A Serilog sink that correlates log events with the code that produced them, enabling unit testing of log output.

A Serilog sink that correlates log events with the code that produced them, enabling unit testing of log output.

Just create a logger that writes or audits to the TestCorrelator.

Log.Logger = new LoggerConfiguration().WriteTo.TestCorrelator().CreateLogger();

Then wrap the code that you would like to monitor with a context and get the log events emitted within that context using the TestCorrelator.

using (TestCorrelator.CreateContext())
{
    Log.Information("My log message!");

    TestCorrelator.GetLogEventsFromCurrentContext()
        .Should().ContainSingle()
        .Which.MessageTemplate.Text
        .Should().Be("My log message!");
}

You can also get a stream of log events as an observable, which can be useful for testing long running or asynchronous tasks.

using (TestCorrelator.CreateContext())
{
    TestCorrelator.GetLogEventStreamFromCurrentContext()
        .Subscribe(logEvent => logEvent.MessageTemplate.Text.Should().Be("My log message!"));

    Log.Information("My log message!");
}

New in v4: If you have more than one logger and want to filter to only log events emitted to a specific sink you can pass in an ID that you then use to filter the log events.

TestCorrelatorSinkId firstTestCorrelatorSinkId = new();
ILogger firstLogger = new LoggerConfiguration().WriteTo.TestCorrelator(firstTestCorrelatorSinkId).CreateLogger();

TestCorrelatorSinkId secondTestCorrelatorSinkId = new();
ILogger secondLogger = new LoggerConfiguration().WriteTo.TestCorrelator(secondTestCorrelatorSinkId).CreateLogger();

using (TestCorrelator.CreateContext())
{
    firstLogger.Information("My first log message!");
    secondLogger.Information("My second log message!");

    TestCorrelator.GetLogEventsForSinksFromCurrentContext(firstTestCorrelatorSinkId)
        .Should().ContainSingle()
        .Which.MessageTemplate.Text
        .Should().Be("My first log message!");

    TestCorrelator.GetLogEventsForSinksFromCurrentContext(secondTestCorrelatorSinkId)
        .Should().ContainSingle()
        .Which.MessageTemplate.Text
        .Should().Be("My second log message!");
}

For more examples check out the unit tests!

Version 4 comes with a few breaking changes.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4