Skip to content

MDC Layout Renderer

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

⚠️ NLog 5.0 introduces ScopeContext that replaces MDLC + MDC

Mapped Diagnostics Context (MDC) - a thread-local structure that keeps a dictionary of strings and provides methods to output them in layouts.

Platforms Supported: All (NLog 4.1 supports any Object type, not just String)

MDC is considered legacy, and instead is recommended to use MDLC that includes support for async Tasks. See also NLog Context

Configuration Syntax

${mdc: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 Diagnostics Context.

MappedDiagnosticsContext.Set("PropertyName", "PropertyValue");
MappedDiagnosticsContext.Set("Property2", new { Part1 = 2.0m, Part2 = "Two parts" });
MappedDiagnosticsContext.Set("Property3", AnyObjectOrString);

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

${mdc:item=PropertyName}
${mdc:item=Property2}
${mdc:item=Property3}

Dynamic Properties

The following example demonstrates a Mapped Diagnostics Context property that renders the value of Environment.TickCount at the time that the context item is rendered.

public class MdcTickProperty 
{
   public static readonly MdcTickProperty Default = new MdcTickProperty();

   private MdcTickProperty () 
   {
   }

   public override string ToString () 
   {
      return Environment.TickCount.ToString();
   }
}

Add the MdcTickProperty instance to the Mapped Diagnostics Context. This will only affect the current thread, as the Mapped Diagnostics Context is thread-local.

MappedDiagnosticsContext.Set("TickCount", MdcTickProperty.Default);

In the logging configuration, include:

${mdc:item=TickCount}

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 (MappedDiagnosticsContext.SetScoped("Property", "PropertyValue")) {
    // "Property" item is present in current context
}
// "Property" item has been removed from current context

Notes

When rendering context items, the item is passed to String.Format along with the current configuration's DefaultCultureInfo value.

Clone this wiki locally