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
