Skip to content

Extends Verify to allow verification of MicrosoftLogging bits.

License

Notifications You must be signed in to change notification settings

SteveDunn/Verify.MicrosoftLogging

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Verify.MicrosoftLogging

Discussions Build status NuGet Status

Extends Verify to allow verification of MicrosoftLogging bits.

See Milestones for release notes.

NuGet package

https://nuget.org/packages/Verify.MicrosoftLogging/

Usage

[ModuleInitializer]
public static void Initialize() =>
    VerifyMicrosoftLogging.Initialize();

snippet source | anchor

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()
{
    var provider = LoggerRecording.Start();
    var target = new ClassThatUsesLogging(provider);

    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";
    }
}

snippet source | anchor

Results in:

{
  target: result,
  logs: [
    {
      Warning: The log entry
    },
    {
      Message: StartScope,
      State: The scope
    },
    {
      Warning: Entry in scope
    },
    {
      Message: EndScope
    }
  ]
}

snippet source | anchor

Typed

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()
{
    var provider = LoggerRecording.Start();
    var logger = provider.CreateLogger<ClassThatUsesTypedLogging>();
    ClassThatUsesTypedLogging target = new(logger);

    var result = target.Method();

    return Verify(result);
}

class ClassThatUsesTypedLogging
{
    ILogger<ClassThatUsesTypedLogging> logger;

    public ClassThatUsesTypedLogging(ILogger<ClassThatUsesTypedLogging> logger) =>
        this.logger = logger;

    public string Method()
    {
        logger.LogWarning("The log entry");
        return "result";
    }
}

snippet source | anchor

Results in:

{
  target: result,
  logs: [
    {
      Warning: The log entry,
      Category: ClassThatUsesTypedLogging
    }
  ]
}

snippet source | anchor

Icon

Logo designed by Ben Davis from The Noun Project.

About

Extends Verify to allow verification of MicrosoftLogging bits.

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 100.0%