Skip to content

ScopeProperty Layout Renderer

Andrey Tomilin edited this page Jun 28, 2023 · 16 revisions

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}

Configuration Syntax

${scopeproperty:item=String}

Parameters

  • 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.

Example

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
}

.NET Core logging

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}
Clone this wiki locally