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} and ${all-event-properties:includeScopeProperties=true}
${scopeproperty:item=String}
@
for Json.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"); }Fallback to default value
When ScopeContext Property cannot be found (or has blank value), then one use whenEmpty to specify fallback value:
${scope-property:UserId:whenEmpty=42}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4