Skip to content

MDLC Layout Renderer

Rolf Kristensen edited this page Aug 29, 2023 · 27 revisions

⚠️ NLog 5.0 introduces ScopeContext that replaces MDLC + MDC

Mapped Diagnostic Logical Context (MDLC) acts like a dictionary of named properties with values, that are stored in an Async-Local structure (Similar to "Thread Context Map" in Log4j). It is the async version of MDC Layout Renderer.

Platforms Supported: All

Introduced with NLog 4.1 (NLog 4.1.1 add support for any Object type, not just String)

It enables one to assign one or more named properties to the active scope (Ex. a request CorrelationId). Then all logger-events created within the scoped logical context, can automatically capture the scope-properties without needing to specify it with each LogEvent. The specified scope properties will automatically flow together with async Tasks.

See also NLog Context.

Configuration Syntax

${mdlc:item=String}

Parameters

Rendering Options

  • item - Name of the item. Required. Note: case sensitive!

Example

Simple Properties

The following example demonstrates the basic usage of the Mapped Diagnostic Logical Context.

MappedDiagnosticsLogicalContext.Set("PropertyName", "PropertyValue");
MappedDiagnosticsLogicalContext.Set("PropertyName2", "AnotherPropertyValue");

Add the following to your logger configuration to reference the above properties.

${mdlc:item=PropertyName}
${mdlc:item=PropertyName2}

Scoped item

The SetScoped method returns an IDisposable that removes the added item when disposed. It can be used in conjunction with the using statement to limit the scope during which the item will be present in the context.

using (MappedDiagnosticsLogicalContext.SetScoped("Property", "PropertyValue")) {
    // "Property" item is present in current context
}
// "Property" item has been removed from current context

.NET Core logging

When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope and more advanced options:

//note: render userId via ${mdlc:userid}
using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("userid", request.UserId) }))
{
   _logger.LogDebug("Start process {ProccessName}, "Main");
}
Clone this wiki locally