Microsoft.Extensions.Logging compatible logger for recording log messages during tests
Install from NuGet:
> dotnet add package InMemoryLogger Then add InMemoryLogger as the logger in your applications service collection:
varservices=newServiceCollection().AddLogging(x =>x.AddInMemory()).BuildServiceProvider();varinMemLogger=services.GetService<InMemoryLogger>();And then write a test that asserts on logs messages:
varlogger=services.GetService<ILogger<MyTest>>();logger.LogWarning("This is a log message");Assert.Contains(inMemLogger.RecordedWarningLogs, l =>l.Message=="This is a log message");Or on logged exceptions:
varlogger=services.GetService<ILogger<MyTest>>();varexpected=newException();logger.LogError(expected,"This is another log message");Assert.Contains(inMemLogger.RecordedErrorLogs, l =>l.Exception==expected);That's it. All logs are in memory, all logs are recorded.