Darthg8r
Darthg8r

Reputation: 12685

NLog with NServiceBus

I'm currently working on a .NET 7 application that utilizes NServiceBus for messaging and NLog for logging purposes. I've set up my application to clear existing logging providers and set the minimum logging level to Trace. Additionally, I'm using NLog as the logging provider for the web host.

In my setup, I've configured NServiceBus's LogManager to use NLog's ExtensionsLoggerFactory. Also, I've registered several services with NServiceBus, including singletons and scoped services like IUnitOfWork.

For logging configuration, my NLog.config includes extensions for NLog.Web.AspNetCore and NLog.Extensions.Logging, among others. I've set up an asynchronous console target with a detailed layout for logging messages, and I've configured a rule to log all messages at the Trace level or higher to this console target.

Despite this configuration, logging works as expected in my controllers and any services injected into these controllers. However, I encounter issues with logging inside NServiceBus message handlers. Specifically, no logs generated inside my SessionRequestAcceptedChatEventHandler message handler appear in the logs. This issue also extends to services injected into my message handlers, where their logs do not appear either.

In my message handler, I inject services like IChatService and IUnitOfWork, along with ILogger. Inside the handler's Handle method, I attempt to log messages at various levels, including Trace, Error, Information, and Warning. However, none of these log messages appear in the output.

What I've Tried: Confirming NLog is configured correctly and working for other parts of the application, such as controllers. Ensuring that the ILogger instance is indeed being injected into the message handler. Modifying log levels in NLog.config to rule out log level filtering as the cause. Searching NServiceBus documentation for any additional logging configurations needed for message handlers. Despite these efforts, the problem remains unresolved.

Question: Has anyone faced similar challenges with logging from within NServiceBus message handlers using NLog in a .NET 7 application? I'm seeking advice on potential causes and solutions for this logging issue. Any insights or suggestions would be greatly appreciated.

Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders().SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);    
builder.WebHost.UseNLog();

NServiceBus.Logging.LogManager.UseFactory(new ExtensionsLoggerFactory(new NLog.Extensions.Logging.NLogLoggerFactory()));

// some other initialization code

endpointConfiguration.RegisterComponents(components =>
{
    components.AddSingleton(cosmosClient);
    components.AddScoped<IUnitOfWork, UnitOfWork>();
});

NLog.config

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
        <add assembly="NLog.Extensions.Logging"/>
        <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
    </extensions>

    <targets async="true">
        <target xsi:type="Console" name="console"
                layout="${date:format=HH\:mm\:ss} ${logger} ${level} ${message} ${exception}" />
    </targets>

    <rules>
        <logger name="*" minlevel="Trace" writeTo="console" />
    </rules>
</nlog>

EventHandler

public class SessionRequestAcceptedChatEventHandler : IHandleMessages<SessionRequestAcceptedEvent>
{
    private readonly IChatService _chatService;
    private readonly IUnitOfWork _unitOfWork;
    private readonly ILogger<SessionRequestAcceptedChatEventHandler> _logger;

    public SessionRequestAcceptedChatEventHandler(IChatService chatService, IUnitOfWork unitOfWork, ILogger<SessionRequestAcceptedChatEventHandler> logger)
    {
        _chatService = chatService;
        _unitOfWork = unitOfWork;
        _logger = logger;
    }
    
    public async Task Handle(SessionRequestAcceptedEvent message, IMessageHandlerContext context)
    {
        _logger.LogTrace("Processing...");
        _logger.LogError("Error occurred");
        _logger.LogInformation("Information");
        _logger.LogWarning("Warning");
      
        await _chatService.SendSessionRequestAcceptedMessage(message.AcceptedBy, message.SessionRequestId, message.TimeAccepted);
        await _unitOfWork.SaveChangesAsync(context);
    }
}

Upvotes: 0

Views: 53

Answers (0)

Related Questions