-
Notifications
You must be signed in to change notification settings - Fork 1.4k
MDLC Layout Renderer
⚠️ NLog 5.0 introduces ScopeContext that replaces MDLC + MDC
Mapped Diagnostic Logical Context (MDLC) acts like a dictionary of named properties with values, that are stored in an Async-Local structure (Similar to "Thread Context Map" in Log4j). It is the async version of MDC Layout Renderer.
Platforms Supported: All
Introduced with NLog 4.1 (NLog 4.1.1 add support for any
Object
type, not justString
)
It enables one to assign one or more named properties to the active scope (Ex. a request CorrelationId). Then all logger-events created within the scoped logical context, can automatically capture the scope-properties without needing to specify it with each LogEvent. The specified scope properties will automatically flow together with async Tasks.
See also NLog Context.
${mdlc:item=String}
- item - Name of the item. Required. Note: case sensitive!
The following example demonstrates the basic usage of the Mapped Diagnostic Logical Context.
MappedDiagnosticsLogicalContext.Set("PropertyName", "PropertyValue");
MappedDiagnosticsLogicalContext.Set("PropertyName2", "AnotherPropertyValue");
Add the following to your logger configuration to reference the above properties.
${mdlc:item=PropertyName}
${mdlc:item=PropertyName2}
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 (MappedDiagnosticsLogicalContext.SetScoped("Property", "PropertyValue")) {
// "Property" item is present in current context
}
// "Property" item has been removed from current context
When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope
and more advanced options:
//note: render userId via ${mdlc:userid}
using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("userid", request.UserId) }))
{
_logger.LogDebug("Start process {ProccessName}, "Main");
}
- 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