Skip to content

ILogger entries are captured twice when a host integration and the NLog, Serilog or log4net integration are both set up #5763

Closed

Description

@jamescrosswell

Problem

An app can set Sentry up through a host integration (UseSentry in ASP.NET Core, the generic host, MAUI and others) and also send ILogger output through NLog, Serilog or log4net with that framework's Sentry integration. In that app, each ILogger entry reaches Sentry twice:

  1. through the ILogger providers that UseSentry registers
  2. through the framework's own ILogger provider, then its pipeline, then the Sentry target, sink or appender

So one LogError("...") call creates two events and two breadcrumbs, and with EnableLogs on, two logs. Errors logged with an exception arrive once, because DuplicateEventDetectionEventProcessor drops the second capture of the same exception instance.

@ric-oliv tested this with Sentry.AspNetCore, Sentry.NLog and Sentry.Log4Net 7.0.0-rc.2, logging one LogError without an exception (comment):

Setup NLog events NLog breadcrumbs log4net events log4net breadcrumbs
UseSentry, then ClearProviders() and the framework's provider 1 1 1 0
ClearProviders() and the framework's provider, then UseSentry 2 2 2 1
Same, with Logging:Sentry:MinimumEventLevel and Logging:Sentry:MinimumBreadcrumbLevel set to None 1 1 1 0

The same happens with NLog's AddNLog() and on the generic host with Sentry.Extensions.Hosting. It isn't new in v7, since 6.12.1 does the same. But more apps will hit it now, because the logging integrations can no longer initialize the SDK and the guides point users to a host integration. Whether an app gets duplicates depends on the order of its init calls, as the first two rows show.

Proposal

When a logging framework's Sentry integration already receives the app's ILogger entries, the host's Sentry ILogger providers stand down. They return a no-op logger and write one diagnostic warning. Each entry then reaches Sentry once, through the framework's integration. This is the pattern HostLoggerProvidersMarker already uses to make Logging.AddSentry() stand down for host integrations (#5694).

  1. The framework integrations register themselves. When SentrySink, SentryTarget or SentryAppender initializes, it records itself in a small internal static registry in Sentry. It can't be a DI marker, because the framework's own configuration creates these objects, not the container. These packages already use Sentry internals, such as UninitializedSdkWarning.
  2. The host providers check lazily, on first log. They look at the registered ILoggerProvider types for the framework bridges: Serilog's SerilogLoggerProvider, NLog's NLogLoggerProvider and the log4net provider (exact type names to confirm). If one is present and that framework's Sentry integration is in the registry, they stand down for events, breadcrumbs and logs.
    • The check can't run at registration time, because registration order is what makes today's outcome inconsistent.
    • It can't run while our provider is being constructed either, because resolving IEnumerable<ILoggerProvider> from inside it would recurse.
    • Once the check succeeds it's cached. Until then the providers keep checking the registry, which is cheap, so a target created after the app's first log is still picked up.

This covers every host integration that registers HostLoggerProvidersMarker: ASP.NET Core, the generic host, MAUI, Blazor WebAssembly and Google Cloud Functions. The result matches what apps get today from "UseSentry, then ClearProviders() and the framework's provider" (the first row above), whatever order the init calls are in.

The framework side has to be the one that wins. The ILogger entries already flow into the framework's pipeline, so nothing is lost. The reverse isn't possible, because the target, sink or appender can't tell which of its entries came from ILogger.

Why not deduplicate each entry

  • No shared object: the two paths don't share any object per entry except the exception, which is already deduplicated. SetFused/GetFused need an object to attach to.
  • Thread-static flags: these depend on which provider runs first, which is set by the app's registration order. They also break under NLog and Serilog async wrappers, which emit on another thread.
  • Dropping identical items at send time: this would also drop genuine repeats, such as the same message logged in a loop.

Trade-offs

  • The framework's routing and levels become the only gate for ILogger entries. For example, NLog rules that only send MyApp.* to the Sentry target, or Serilog's MinimumLevel.Override("Microsoft", LogEventLevel.Warning), would now drop Microsoft.* entries that the host provider captured before. Unhandled exceptions still arrive through the host's middleware.
  • The host's settings stop applying to ILogger entries: MinimumEventLevel, MinimumBreadcrumbLevel, EnableLogs and log entry filters. The diagnostic warning should say so.
  • A Serilog sink on a different logger from the one the bridge writes to would lose entries silently. This is rare.
  • The reverse direction isn't covered. Serilog's UseSerilog(writeToProviders: true) sends Serilog's own events into Sentry's ILogger provider, which duplicates the other way. That needs a separate check on the ILoggerFactory type, or we accept it as an edge case.

The alternative is to detect the same situation but only warn, with the workaround of setting the Logging:Sentry levels to None, and change no behaviour. Standing down is a behaviour change, so it fits 7.0, where these integrations already changed how they start. If it lands, the docs note requested in getsentry/sentry-docs#19925 shrinks to one sentence explaining which side handles ILogger entries.

Related

Activity

  1. added
    Bug
    .NET
    Next Major
    on Oct 22, 2026
  2. linear-code commented on Oct 22, 2026

    @linear-code
  3. added this to the 7.0.0 milestone on Oct 22, 2026
  4. jamescrosswell commented on Oct 27, 2026

    @jamescrosswell
    CollaboratorAuthor

    Two things changed since this was filed:

    Minor: #5789's warning now fires on row 1, and its main advice — call AddSentry() to add the providers back — would create the duplicates described here. Worth rewording if standing down lands.

  5. jamescrosswell commented on Oct 27, 2026

    @jamescrosswell
    CollaboratorAuthor

    For Serilog, the recommended setup doesn't duplicate.

    builder.Host.UseSerilog(...) replaces the ILoggerFactory with Serilog's own, and that factory ignores every ILoggerProvider in the container, so the providers UseSentry registers never run. Duplicates only appear when Serilog is added as a provider next to Sentry's, or when Serilog writes back into the providers.

    I tested the Sentry.Samples.AspNetCore.Serilog sample on main (Serilog.AspNetCore 6.1.0) against a mock Sentry endpoint. Each row is one logger.LogError("...") with no exception:

    Setup Events Breadcrumbs per LogInformation
    builder.Host.UseSerilog(...) (recommended) 1 1
    builder.Host.UseSerilog(..., writeToProviders: true) 2 2
    builder.Logging.ClearProviders(); builder.Logging.AddSerilog();, then UseSentry 2 2

    So for Serilog this would only be a problem if someone initialised it using Log.Logger.WriteTo.Sentry rather than builder.Host.UseSentry... basically it doesn't work when people set it up wrong. I'll check NLog and log4net next.

  6. jamescrosswell commented on Oct 27, 2026

    @jamescrosswell
    CollaboratorAuthor

    After digging into this, I think it's working as designed and needs documenting, not an SDK change.

    ILogger<T> writes through ILoggerFactory, and the default factory sends each entry to every registered ILoggerProvider. UseSentry registers Sentry's providers. If the app registers another provider that also feeds Sentry, each entry reaches Sentry twice, as you'd expect from two providers. Users get caught because UseSentry adds its providers implicitly, so they may not realise they have two paths into Sentry.

    ClearProviders() only removes providers registered before it runs. When UseSentry comes first it removes Sentry's providers too, which is why the order of the init calls decides the outcome in the table above.

    I reproduced every case below on main against a mock Sentry endpoint (repro: jamescrosswell/sentry-dotnet@repro/5763-ilogger-duplicates, see Sentry.Samples.AspNetCore.Basic). version7 registers and filters these providers the same way.

    Footguns and correct setups

    Serilog

    • Footguns
      • ClearProviders() + AddSerilog(), then UseSentry
        • AddSerilog() adds Serilog as a provider next to Sentry's, so each entry reaches Sentry directly and again through the Serilog sink. With UseSentry first it doesn't duplicate, but only because ClearProviders() removed Sentry's providers.
      • UseSerilog(..., writeToProviders: true)
        • Serilog sends its events back into the registered providers, Sentry's included, so they arrive through Sentry's provider and again through the sink.
    • Correct
      • builder.Host.UseSerilog(...)
        • This replaces the ILoggerFactory with Serilog's own, which ignores the registered providers. Sentry's providers never run, and everything reaches Sentry once, through the sink.

    NLog

    • Footguns
      • builder.Host.UseNLog() / builder.Logging.AddNLog() (the default setup), then UseSentry
        • NLog adds itself as a provider next to Sentry's, so each entry reaches Sentry directly and again through the Sentry target. With UseSentry first and ClearProviders() between them it doesn't duplicate, but only because Sentry's providers were removed.
    • Correct
      • builder.Host.UseNLog(new NLogAspNetCoreOptions { ReplaceLoggerFactory = true })
        • NLog's factory replaces the default one, just as UseSerilog does. One event in either order.

    log4net (Microsoft.Extensions.Logging.Log4Net.AspNetCore, a third-party package)

    • Footguns
      • builder.Logging.AddLog4Net(), then UseSentry
        • It adds log4net as a provider next to Sentry's, so each entry reaches Sentry directly and again through the appender. This package has no option to replace the factory.
    • Correct
      • Turn off Sentry's ILogger capture with config: Logging:Sentry:MinimumEventLevel and Logging:Sentry:MinimumBreadcrumbLevel set to None (Sentry: works too), plus Logging:Sentry:LogLevel:Default set to None.
        • Each setting is needed. The min levels stop the duplicate events and breadcrumbs, but the event provider ignores LogLevel config (UseSentry gives it a delegate filter), so structured logs still duplicate until the LogLevel filter turns off Sentry's log provider. Without the LogLevel setting I got 1 event, 1 breadcrumb and 2 logs. With it, 1 of each. Levels set in code in the UseSentry callback override the config.
      • Or call UseSentry first, then ClearProviders() + AddLog4Net(). Also 1 of each, but it depends on call order, and it triggers the fix(logging): warn when ClearProviders() removes the logger providers UseSentry added #5789 warning.

    Proposed changes

    sentry-dotnet

    • Samples: none need changing. Sentry.Samples.AspNetCore.Serilog already uses UseSerilog(...), and there's no hosted NLog or log4net sample.
    • We could add an NLog sample since the setup for NLog is less intuitive than Serilog and NLog is a fairly popular logging framework
    • version7 warning text and XML docs:
      • HostLoggerProvidersRemoved in SentryLoggingOptions.cs (fix(logging): warn when ClearProviders() removes the logger providers UseSentry added #5789) leads with "call AddSentry() … to add them back". For an app that sends ILogger through NLog, Serilog or log4net, that advice creates these duplicates. Lead with that case instead: it's expected, and calling AddSentry() would send everything twice.
      • The AddSentry() remarks in LoggingBuilderExtensions.cs (both overloads) should say the same.
    • Drop the stand-down proposal at the top of this issue.

    sentry-docs (in getsentry/sentry-docs#19925 or a follow-up)

    • platform-includes/logs/setup/dotnet.mdx: both paragraphs say to leave EnableLogs off when another framework is an ILogger provider. That stops duplicate logs, but events and breadcrumbs still duplicate, and the example given (builder.Logging.AddSerilog()) is itself a footgun. Point to the per-framework setup below instead.
    • Serilog guide: recommend builder.Host.UseSerilog(...) for host apps, and warn against AddSerilog() and writeToProviders: true alongside UseSentry.
    • NLog guide: add a host-app section that uses UseNLog(new NLogAspNetCoreOptions { ReplaceLoggerFactory = true }).
    • log4net guide: add a host-app section with the three config settings above, and the ordering alternative with its caveats.
  7. ric-oliv commented on Oct 29, 2026

    @ric-oliv
    Member

    @jamescrosswell Should we also close this issue now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

.NETBugLogsMicrosoft.Extensions.LoggingNLogNext MajorSerilogState: Needs Discussionlog4net

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions