Skip to content

Gdc layout renderer

Rolf Kristensen edited this page May 9, 2025 · 22 revisions

Global Diagnostic Context (GDC) - Dictionary structure for global settings for the entire application-instance.

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

GDC properties should be assigned at application-startup and remain static and immutable during the lifetime of the application/process. Do NOT modify the GDC as part of the logging operations, as it will have unwanted side-effects. If needing to include additional context information for a specific logevent, then consider using Logger.WithProperty() or Logger.PushScopeProperty().

See also NLog Context.

Configuration Syntax

${gdc:item=String}

Parameters

Rendering Options

  • item - Name of the item. Required. Note Before NLog 5.0 it was case-sensitive.
  • culture - The culture used for rendering. Introduced in NLog 5.0. Default value is CultureInfo.InvariantCulture
  • format - Format for conversion from object to string. Introduced in NLog 4.5.
    • @ means serialize object properties into Json-format.

Example

Simple Properties

The following example demonstrates the basic usage of the Global Diagnostics Context.

GlobalDiagnosticsContext.Set("myDataBase","someValue");
GlobalDiagnosticsContext.Set("informationGroup", new { One = 1, Two = 2 });
GlobalDiagnosticsContext.Set("anyObject", anyObjectReferenceOrString);

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

${gdc:item=myDatabase}
${gdc:item=informationGroup}
${gdc:item=anyObject}

Dynamic Properties

The Global Diagnostics Context (GDC) can also store complex objects, and can be used as an alternative to registering own custom layout renderer. NLog sees the GDC like global variables that doesn't depend on thread execution context, so make sure any complex object logic doesn't depend on application logging thread-state.

public class ApplicationStateProperty : IFormattable
{
   public static readonly ApplicationStateProperty Default = new ApplicationStateProperty();

   private ApplicationStateProperty() 
   {
   }

   public override string ToString()
   {
      // Physical memory used by application process (in megabytes)
      return ((long)(System.Environment.WorkingSet / (1024 * 1024))).ToString();
   }

   string IFormattable.ToString(string format, IFormatProvider formatProvider)
   {
      return ToString();
   }
}

During initialization, add the following code:

GlobalDiagnosticsContext.Set("AppMemorySize", ApplicationStateProperty.Default);

To reference the AppMemorySize Global Diagnostics Context property.

${gdc:item=AppMemorySize}

Notes

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

Clone this wiki locally