Microsoft Logging

Project Hosting
NuGet Package NServiceBus.MicrosoftLogging (1-pre) | License
This is a community run project. License and support are independent of Particular Software.
Target NServiceBus Version: 7.x
This page targets a pre-release version and is subject to change prior to the final release.

Support for writing all NServiceBus log entries to Microsoft.Extensions.Logging.

Usage

using (var loggerFactory = new LoggerFactory())
{
    loggerFactory.AddConsole();
    var logFactory = LogManager.Use<MicrosoftLogFactory>();
    logFactory.UseMsFactory(loggerFactory);
    // endpoint startup and shutdown
}

Usage when hosting

As LoggerFactory implements IDisposable it must be disposed of after IEndpointInstance.Stop has been called. The process for doing this will depend on how the endpoint is being hosted.

In a windows service

When hosting in a windows service LoggerFactory should be disposed of as part of the ServiceBase.OnStop execution.

[DesignerCategory("Code")]
class ProgramService :
    ServiceBase
{
    IEndpointInstance endpointInstance;
    LoggerFactory loggerFactory;

    static void Main()
    {
        using (var service = new ProgramService())
        {
            if (ServiceHelper.IsService())
            {
                Run(service);
                return;
            }
            service.OnStart(null);
            Console.WriteLine("Bus started. Press any key to exit");
            Console.ReadKey();
            service.OnStop();
        }
    }

    protected override void OnStart(string[] args)
    {
        AsyncOnStart().GetAwaiter().GetResult();
    }

    async Task AsyncOnStart()
    {
        loggerFactory = new LoggerFactory();
        loggerFactory.AddConsole();
        var logFactory = LogManager.Use<MicrosoftLogFactory>();
        logFactory.UseMsFactory(loggerFactory);
        var endpointConfiguration = new EndpointConfiguration("EndpointName");
        endpointConfiguration.EnableInstallers();
        endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
    }

    protected override void OnStop()
    {
        AsyncOnStop().GetAwaiter().GetResult();
    }

    async Task AsyncOnStop()
    {
        if (endpointInstance != null)
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
        loggerFactory?.Dispose();
    }
}

Samples

Related Articles

  • Logging
    Manage and integrate with NServiceBus logging.

Last modified