You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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:
varlogger=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:
using(_logger.BeginScope(new[]{newKeyValuePair<string,object>("userid",request.UserId)})){_logger.LogDebug("Hello {World}","Earth");// Render userId via ${scopeproperty:userid} in target output}
NLog.Extensions.Logging v5.3.7 adds support for using ValueTuple for single scope-property (better performance):
using(_logger.BeginScope(("userid",request.UserId))){_logger.LogDebug("Hello {World}","Earth");// Render userId via ${scopeproperty:userid} in target output}
Fallback to default value
When ScopeContext Property cannot be found (or has blank value), then one use whenEmpty to specify fallback value: