This sample shows how to configure an NServiceBus endpoint to use NLog through the Microsoft. abstractions.
Both Microsoft.Extensions.Logging and NServiceBus.Logging are logging abstractions and both must be configured.
The following logging chain is created:
- NServiceBus.Logging
- Microsoft.Extensions.Logging
- NLog.Extensions.Logging
- NLog
- Console output
- NLog
- NLog.Extensions.Logging
- Microsoft.Extensions.Logging
Starting with NServiceBus 10.2, endpoints hosted with the .NET Generic Host using AddNServiceBusEndpoint automatically integrate with Microsoft. and the NServiceBus. bridge package is no longer required. This sample demonstrates the modern approach.
Configure NLog
NLog in this example is configured in code:
var config = new LoggingConfiguration();
var consoleTarget = new ColoredConsoleTarget
{
Layout = "${level}|${logger}|${message}${onexception:${newline}${exception:format=tostring}}"
};
config.AddTarget("console", consoleTarget);
config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget));
NLog.LogManager.Configuration = config;
There is no preference on how NLog is configured. Based on the NLog documentation, the most used method is with an NLog configuration file.
When using self-hosted endpoints, it is important that the NLog and Microsoft.Extensions.Logging abstractions are initialized before Endpoint. is invoked. When hosting with the .NET Generic Host, logging providers are registered on the host builder and the initialization is handled automatically by the host lifecycle.
Configure logging abstractions
The following snippet shows how to register NLog as a logging provider. NLog has its own provider extensions for Microsoft.Extensions.Logging and needs an NLogLoggerFactory provider that implements an Microsoft. instance so that Microsoft. can use NLog.
builder.Logging.AddNLog(config);
Endpoints can be created or started only after the logging initialization has completed.