-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Gdc layout renderer
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 justString
)
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.
${gdc:item=String}
- 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.
-
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}
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}
When rendering context items, the item is passed to String.Format
along with the current configuration's DefaultCultureInfo
value.
- Troubleshooting Guide - See available NLog Targets and Layouts: https://nlog-project.org/config
- Getting started
- How to use structured logging
- Troubleshooting
- FAQ
- Articles about NLog
-
All targets, layouts and layout renderers
Popular: - Using NLog with NLog.config
- Using NLog with appsettings.json