-
Notifications
You must be signed in to change notification settings - Fork 1.4k
MDC Layout Renderer
⚠️ 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 justString
)
MDC is considered legacy, and instead is recommended to use MDLC that includes support for async Tasks. See also NLog Context
${mdc:item=String}
- item - Name of the item. Required. Note: case sensitive!
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}
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}
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
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