-
Notifications
You must be signed in to change notification settings - Fork 1.4k
ScopeNested Layout Renderer
ScopeContext Nested States are stored in the thread execution context. Similar to "Nested Diagnostic Context" (NDC) 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 a scope-name to the active scope (Ex. a request method-name). Then all logger-events created within the scoped logical context, can automatically capture the scope-name without needing to specify it with each LogEvent. The specified scope states will automatically flow together with async Tasks.
See also NLog Context and ${scopeproperty} and ${scopetiming} and ${scopeindent}
${scopenested:bottomFrames=Integer:topFrames=Integer:separator=String}
-
bottomFrames - Number of bottom stack frames to be rendered.
-1
is no limit.Integer
. Default-1
. -
topFrames - Number of top stack frames to be rendered.
-1
is no limit.Integer
. Default-1
-
separator - Separator to be used for concatenating nested diagnostics context output.
string
. Default -
format - Format string for conversion into string. Possible to use
@
for Json-Array. - culture - Format provider for conversion into string.
using (NLog.ScopeContext.PushNestedState("Outer Scope"))
{
Logger.Info("Hello Outer");
await InnerOperationAsync();
}
static async Task InnerOperationAsync()
{
using (NLog.ScopeContext.PushNestedState("Inner Scope"))
{
Logger.Info("Hello Inner");
await Task.Yield();
}
}
The NLog Logger
can also be used to update ScopeContext:
var logger = NLog.LogManager.GetCurrentClassLogger();
using (logger.PushScopeNested("Outer Scope"))
{
}
When using NLog.Extensions.Logging or NLog.Web.AspNetCore, you can also use BeginScope
and more advanced options:
using (_logger.BeginScope("Outer Scope"))
{
_logger.LogDebug("Start process {ProccessName}, "Main");
}
Indent log-messages based on how many nested levels in ScopeContext using ${scopeindent}
${scopeindent}${message}
- 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