Skip to content

Gdc layout renderer

Rolf Kristensen edited this page Oct 19, 2024 · 19 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 try to 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

In some instances you may have thread-local information that you want to make available to all logger instances in the current process. This can be achieved with the Mapped Diagnostics Context, but requires that your create the property within the context of every thread that may reference it. Using Dynamic Properties and the Global Diagnostics Context, you can achieve the same result while only creating the property once.

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

   private ManagedThreadIdProperty () 
   {
   }

   public override string ToString ()
   {
      return System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
   }

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

During initialization, add the following code:

GlobalDiagnosticsContext.Set("ManagedThreadId", ManagedThreadIdProperty.Default);

To reference the ManagedThreadId Global Diagnostics Context property.

${gdc:item=ManagedThreadId}

Notes

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

Clone this wiki locally