Skip to main content
Version: Next

Test framework logging

This page describes functionality related to logging in tests.

The Arcus.Testing.Logging.Xunit library provides a XunitTestLogger type that's an implementation of the abstracted Microsoft Ilogger inside the xUnit test framework.

Installation

The following functionality is available when installing this package:

PM> Install-Package -Name Arcus.Testing.Logging.Xunit

Example

Log messages written to the ILogger instance will be written to the xUnit test output.

using Arcus.Testing;
using Microsoft.Extensions.Logging;
using Xunit.Abstractions;

public class TestClass
{
private readonly ILogger _testLogger;

public TestClass(ITestOutputHelper outputWriter)
{
_testLogger = new XunitTestLogger(outputWriter);
}
}

In the same fashion there is a:

  • [XunitTestLogging] extension to add a Serilog log sink for an ITestOutputHelper that delegates written log emits to the xUnit test output,
  • [AddXunitTestLogging] extension to add a ILoggerProvider to a Microsoft Logging setup.

In-memory test logging

The Arcus.Testing.Logging.Core library provides a InMemoryLogger and InMemoryLogger<T> which are ILogger and ILogger<T> implementations respectively. These types help in tracking logged messages and their metadata information like the level on which the message was logged or the related exception.

using Arcus.Testing;
using Microsoft.Extensions.Logging;

ILogger logger = new InMemoryLogger();

logger.LogInformation("This is an informational message");

// Either get the message directly, or
IEnumerable<string> messages = logger.Messages;

// Use the full `LogEntry` object to retrieve the message.
IEnumerable<LogEntry> entries = logger.Entries;
LogEntry entry = entries.First();

// Level = Information
LogLevel level = entry.Level;
// Message = "This is a informational message"
string message = entry.Message;

Or, alternatively you can use the generic variant:

using Arcus.Testing;
using Microsoft.Extensions.Logging;

ILogger<MyType> logger = new InMemoryLogger<MyType>();

logger.LogInformation("This is an informational message");

IEnumerable<string> messages = logger.Messages;

Serilog in-memory log sink

The Arcus.Testing.Logging.Core library provides a InMemoryLogSink which is a Serilog log sink that collectes written log emits in-memory so the test infrastructure can assert on the actual rendered messages and possible properties available on the log emit.

using Arcus.Testing;
using Serilog;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Events;

var logSink = new InMemoryLogSink();
var logger = new LoggerConfiguration()
.WriteTo.Sink(logSink)
.CreateLogger();

logger.Information("This is an informational message");

IEnumerable<LogEvent> emits = logSink.CurrentLogEmits;
IEnumeratble<string> messages = logSink.CurrentLogMessages;