liveBook · Manning

Logging scope

As explained in ASP.NET Core in Action, 3e

A logging scope is a contextual logging construct that associates additional data with log messages emitted during a bounded execution context.

A logging scope groups related operations and attaches shared context to every log message emitted within a bounded using block. It is especially useful with structured logging providers because the added data can be searched and filtered. section 26.5.1 section 26.5.2

Attach properties to a group of logs

using (_logger.BeginScope(new Dictionary<string, object> { { "RecipeId", 3245 } })) { _logger.LogInformation("Loading recipe"); _logger.LogInformation("Validating recipe"); } Both messages carry RecipeId. Messages written before or after the using block do not. A scope can also contain a string, integer, or other object, but dictionaries are typically more useful because their entries become structured properties. section 26.5.2

Listing 26.8 Adding scope properties to log messages with BeginScope
_logger.LogInformation("No, I don't have scope");        #1
using(_logger.BeginScope("Scope value"))                 #2
using(_logger.BeginScope(new Dictionary<string, object>  #3
    {{ "CustomValue1", 12345 } }))                       #3
{
    _logger.LogInformation("Yes, I have the scope!");    #4
}
_logger.LogInformation("No, I lost it again");           #1

Use the annotated listing to compare logs outside a scope, inside nested scopes, and after scope disposal. section 26.5.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines scopes, demonstrates BeginScope with using blocks, and explains provider-specific state serialization and structured properties.
Examples
Uses recipe IDs, transaction IDs, user IDs, nested scopes, dictionaries, and Seq searches to demonstrate correlated logs.
What it assumes
Assumes familiarity with ASP.NET Core logging and ILogger, while teaching scope creation and lifetime from the basic API call.
What you can do after
Apply it via ILogger.BeginScope to correlate and filter related log messages with shared structured properties.
How it connects
Connects logging scopes with structured logging, logging providers, ILogger, and log querying.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.