-
Notifications
You must be signed in to change notification settings - Fork 1.4k
ScopeProperty Layout Renderer
ScopeContext Properties are stored in the thread execution context. Similar to "Mapped Diagnostic Context" (MDC) in Log4j.
Platforms Supported: All (AsyncLocal is used for NetStandard and Net46, but older platforms uses
Remoting.Messaging.CallContext
)
Introduced with NLog 5.0 that merges ${MDC} + ${MDLC} + ${NDC} + ${NDLC} into an unified ScopeContext.
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 include the scope-properties in the ouput without specifying with each LogEvent. The specified scope properties will automatically flow together with async Tasks.
See also NLog Context and ${scopenested} and ${scopetiming}
${scopeproperty:item=String}
- item - Name of the item. Lookup is case-insensitive. Required.
-
format - Format string for conversion into string. Possible to use
@
for Json. - culture - Format provider for conversion into string.
using (NLog.ScopeContext.PushProperty("PropertyName", "PropertyValue"))
{
Logger.Info("Hello World"); // LogEvent can use ${scopeproperty:PropertyName} in target output
}
// "PropertyName" items has been removed from current context
The NLog Logger
can also be used for updating the ScopeContext:
var logger = NLog.LogManager.GetCurrentClassLogger();
using (logger.PushScopeProperty("PropertyName", "PropertyValue"))
{
logger.Info("Hello World"); // LogEvent can use ${scopeproperty:PropertyName} in target output
}
When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope
and more advanced options:
//note: render userId via ${scopeproperty:userid}
using (_logger.BeginScope(new[] { new KeyValuePair<string, object>("userid", request.UserId) }))
{
_logger.LogDebug("Start process {ProccessName}", "Main");
}
When ScopeContext Property cannot be found (or has blank value), then one use whenEmpty to specify fallback value:
${scope-property:UserId:whenEmpty=42}
- 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