ASP.NET Core Interview Question #157
What is a logging scope?
Logging, Error Handling & Background Services Mid-Level Intermediate
Quick Interview Answer
A logging scope attaches contextual information to a group of log entries produced during an operation. Providers that support scopes can include this context in every log event inside the scope.
Detailed Explanation
A logging scope attaches contextual information to a group of log entries produced during an operation. Providers that support scopes can include this context in every log event inside the scope.
Scopes are useful for correlation identifiers, job identifiers, tenant IDs, or other operation-level context. They reduce the need to manually repeat the same property in every logging statement.
Scopes should contain useful diagnostic identifiers rather than sensitive data.
Code Example
using (_logger.BeginScope(
new Dictionary<string, object>
{
["OrderId"] = orderId,
["CorrelationId"] = correlationId
}))
{
_logger.LogInformation("Starting order processing");
await ProcessOrderAsync(orderId);
_logger.LogInformation("Finished order processing");
}