Skip to content

feat: support BeginScope of Microsoft.Extensions.Logging for Structured Logs #5222

Open

Description

@Flash0ver

Description

Summary

Attach state
and FormattedLogValues (IReadOnlyList<KeyValuePair<string, object?>> or IEnumerable<KeyValuePair<string, object?>>)
provided via the IDisposable-returning BeginScope (instance and extension) methods
as Attributes to Logs.

Remarks

APIs to support

Consider using Microsoft.Extensions.Logging.IExternalScopeProvider as implementation detail.

Consider supporting a boolean IncludeScopes option, that e.g. the Console-Logger exposes.

See docs at Logging in C# and .NET > Log scopes.

Activity

  1. added
    .NET
    on May 12, 2026
  2. linear-code commented on May 12, 2026

    @linear-code
  3. added
    Feature
    on May 12, 2026
  4. changed the title [-]feat: support `Microsoft.Extensions.Logging`[/-] [+]feat: support `BeginScope` of `Microsoft.Extensions.Logging` for Structured Logs[/+] on May 12, 2026
  5. jamescrosswell commented on May 12, 2026

    @jamescrosswell
    Collaborator

    How does this relate to the current functionality?

    #if NET8_0_OR_GREATER
    public IDisposable BeginScope<TState>(TState state) where TState : notnull
    => _hub.PushScope(state);
    #else
    public IDisposable BeginScope<TState>(TState state) => _hub.PushScope(state);
    #endif

    How would the behaviour differ after this change?

  6. added
    Next Major
    on May 27, 2026
  7. Flash0ver commented on May 27, 2026

    @Flash0ver
    ContributorAuthor

    Wasn't thinking about the Event/Breadcrumb-Integration.
    If we had Attributes on the Scope, than we could just apply the Attributes of the current Scope (Stack of Scopes) to the Logs (and Metrics as well).
    Currently, the information is on the Scope as "Tags" only, but there might be more info in the Tags that user code might not expect to be converted (in a minor release) to Attributes.

  8. Flash0ver commented on Jul 9, 2026

    @Flash0ver
    ContributorAuthor

    We actually need both - so I believe:

    The Logging APIs to add Attributes to Logs under the Logger-Scope:

    if (logger.IsEnabled(LogLevel.Information))
    {
        using (logger.BeginScope(new Dictionary<string, object>(3) { {"A", 1}, {"B", 2}, {"C", 3}, }))
        {
            logger.LogInformation("first");
        }
    
        using (logger.BeginScope("A={0}, B={1}, C={2}", 1, 2, 3)) //extension method that invokes ILogger.BeginScope with Microsoft.Extensions.Logging.FormattedLogValues
        {
            logger.LogInformation("second");
        }
    }

    as well as our APIs via Sentry-Attributes on the respective Scope:

    if (!options.IsGlobalModeEnabled)
    {
        using (SentrySdk.PushScope(new Dictionary<string, object>(3) { {"A", 1}, {"B", 2}, {"C", 3}, }))
        {
            logger.LogInformation("third");
        }
    }

    Considering precedence:
    Which Attributes should have a higher precedence and potentially overwrite the other Attributes (if the same key)?

    • Logger-Scope > Sentry-Scope
    • Sentry-Scope > Logger-Scope

    I'm currently leaning towards first applying Scope-Attributes, then the Attributes from the Logger-Scope to potentially overwrite previously set Attributes, as the Logger-Scope is "closer" to the ILogger then our Sentry-Scope.

  9. jamescrosswell commented on Oct 20, 2026

    @jamescrosswell
    Collaborator

    Plan for this one:

    Scope: only ILogger.BeginScope → attributes on Structured Logs. Attributes on the Sentry Scope (SentrySdk.PushScope(...) in the example above) are deferred to #4882, along with the precedence rules between the layers. Once #4882 lands, logger-scope attributes slot in above the Sentry-scope ones, as suggested above.

    Opt-in on main: this ships behind a new IncludeScopes option on SentryLoggingOptions, defaulting to false, so it doesn't need to wait for v7. Off by default since ASP.NET Core opens a logging scope for every request (RequestId, RequestPath, ConnectionId, and TraceId/SpanId depending on ActivityTrackingOptions). Turning it on adds those attributes to every log in every ASP.NET Core app. We can revisit the default for the next major.

    Likely implementation:

    • SentryStructuredLoggerProvider implements ISupportExternalScope. LoggerFactory then hands it the shared IExternalScopeProvider and manages the scope stack itself, so SentryStructuredLogger.BeginScope can stay a no-op.
    • When IncludeScopes is on, SentryStructuredLogger.Log walks IExternalScopeProvider.ForEachScope and flattens each scope's state into log.Attributes. The existing FormattedLogValues parsing in Log can be shared, so both BeginScope(IEnumerable<KeyValuePair<string, object?>>) and the BeginScope(string, params object?[]) extension are covered.
    • Add IncludeScopes to SentryLoggingOptions and BindableSentryLoggingOptions, and accept the API snapshot changes.
    • The events/breadcrumbs SentryLogger is unchanged: scope state still becomes tags.

    Decisions to settle in the PR:

    • Non-key/value scopes (BeginScope("some string") or an arbitrary object): map them to a single attribute or drop them.
    • {OriginalFormat} from FormattedLogValues scopes: probably drop it, since it's the template, not data.
    • Key conflicts: inner scopes win over outer ones. I'd also recomment the log's own message parameters win over scope attributes.
    • Value types: convert values to the supported attribute types, with ToString() as the fallback.
  10. removed
    Next Major
    on Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETExplore > LogsFeatureLogsMicrosoft.Extensions.Logging

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions