Getting started

edit

The examples of this documentation omit the using directives: see Namespaces.

Write the logs of an application to files

Add the package:

dotnet package add Meziantou.Extensions.Logging.FileLogger

Register the provider on the logging builder of the host. Host is in the Microsoft.Extensions.Hosting namespace:

var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddFile(options =>
{
    options.Directory = "logs";
    options.RollInterval = RollInterval.Daily;
    options.MaxRetainedFiles = 7;
});

The messages are written to the logs directory, in a new file every day, and only the last 7 files are kept. See File logger.

Assert on the logs in a test

Add the package to the test project:

dotnet package add Meziantou.Extensions.Logging.InMemory

Create a logger, pass it to the code under test, and assert on the entries it collected:

// Create a logger directly
var logger = InMemoryLogger.CreateLogger("MyCategory");
logger.LogInformation("Test message");

// Access captured logs
Assert.Single(logger.Logs.Informations);
Assert.Contains(logger.Logs, log => log.Message == "Test message");

See In-memory logger.

Show the logs in the output of a test

Add the package to a test project that uses xUnit.net v3:

dotnet package add Meziantou.Extensions.Logging.Xunit.v3

Create a logger that writes to the output of the test:

public sealed class MyTests(ITestOutputHelper testOutputHelper)
{
    [Fact]
    public void MyTest()
    {
        var logger = XUnitLogger.CreateLogger(testOutputHelper);
        logger.LogInformation("This message will appear in the test output");
    }
}

The message is shown with the result of the test. See xUnit.net logger.