Extends Verify to allow verification of MicrosoftLogging bits.
See Milestones for release notes.
https://nuget.org/packages/Verify.MicrosoftLogging/
[ModuleInitializer]
public static void Initialize() =>
VerifyMicrosoftLogging.Initialize();
Logging Recording allows, when a method is being tested, for any logging made as part of that method call to be recorded and verified.
Call LoggerRecording.Start();
to get an instance of the LoggerProvider
. LoggerProvider
implements both ILogger
and ILoggerProvider
.
The pass in the LoggerProvider
instance to a class/method that write log entries:
[Fact]
public Task Logging()
{
Recording.Start();
var logger = new RecordingLogger();
var target = new ClassThatUsesLogging(logger);
var result = target.Method();
return Verify(result);
}
class ClassThatUsesLogging(ILogger logger)
{
public string Method()
{
logger.LogWarning("The log entry");
using (logger.BeginScope("The scope"))
{
logger.LogWarning("Entry in scope");
}
return "result";
}
}
Results in:
{
target: result,
log: [
{
Warning: The log entry
},
{
Message: StartScope,
State: The scope
},
{
Warning: Entry in scope
},
{
Message: EndScope
}
]
}
A common pattern is to use a type logger (Logger<T>
). LoggerProvider
provides a builder method CreateLogger<T>
to construct a Logger<T>
:
[Fact]
public Task LoggingTyped()
{
Recording.Start();
var logger = RecordingProvider.CreateLogger<ClassThatUsesTypedLogging>();
var target = new ClassThatUsesTypedLogging(logger);
var result = target.Method();
return Verify(result);
}
class ClassThatUsesTypedLogging(ILogger<ClassThatUsesTypedLogging> logger)
{
public string Method()
{
logger.LogWarning("The log entry");
return "result";
}
}
Results in:
{
target: result,
log: {
Warning: The log entry,
Category: ClassThatUsesTypedLogging
}
}
Log designed by Ben Davis from The Noun Project.