Skip to content

MicrosoftILogger Target

Rolf Kristensen edited this page Dec 28, 2022 · 5 revisions

Forwards messages to Microsoft Extensions Logging (MEL) ILogger-interface.

Introduced with NLog.Extensions.Logging ver. 1.5.0

Target can be used in Azure functions for capturing output from existing components that already uses NLog Loggers.

Target can also be used for transforming standard log-messages into Json-output.

Configuration Parameters

  • EventId - Layout for rendering ILogger EventId Layout
  • EventName - Layout for rendering ILogger EventName Layout
  • includeMdlc - Include contents of the async MappedDiagnosticsLogicalContext dictionary. Boolean
  • ContextProperties - Collection of additional context properties
    • Name - Name of context property
    • Layout - Value for the context property Layout

Example

var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger);
var nlogConfig = new NLog.Config.LoggingConfiguration();
nlogConfig.AddRuleForAllLevels(loggerTarget);
NLog.LogManager.Configuration = nlogConfig;
var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
nlogLogger.Info("Hello {planet}", "Earth");

Example with extra context properties

var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger);
loggerTarget.IncludeMdlc = true;
loggerTarget.ContextProperties.Add(new TargetPropertyWithContext("threadid", "${threadid}"));
loggerTarget.ContextProperties.Add(new TargetPropertyWithContext("hostname", "${hostname}"));

var nlogConfig = new NLog.Config.LoggingConfiguration();
nlogConfig.AddRuleForAllLevels(loggerTarget);
NLog.LogManager.Configuration = nlogConfig;
var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
using (NLog.MappedDiagnosticsLogicalContext.SetScoped("TraceId", Guid.NewGuid())
{
   nlogLogger.Info("Hello {planet}", "Earth");
}

Example with JsonLayout

var jsonLayout = new NLog.Layouts.JsonLayout();
jsonLayout.IncludeEventProperties = true;
var loggerTarget = new NLog.Extensions.Logging.MicrosoftILoggerTarget(azureILogger) { Layout = jsonLayout };
var nlogConfig = new NLog.Config.LoggingConfiguration();
nlogConfig.AddRuleForAllLevels(loggerTarget);
NLog.LogManager.Configuration = nlogConfig;
var nlogLogger = NLog.LogManager.GetCurrentClassLogger();
nlogLogger.Info("Hello {planet}", "Earth");
Clone this wiki locally