Skip to content

Commit d2e7281

Browse files
feat: Microsoft.Extensions.Logging integration no longer initializes the SDK
Completes the logging-integration part of #5245. The MEL integration now only wires up the logger providers; Sentry has to be initialized separately. Unlike Serilog, NLog and log4net, SentryLoggingOptions keeps deriving from SentryOptions, because SentryAspNetCoreOptions, SentryMauiOptions and SentryBlazorOptions derive from it and those integrations do initialize the SDK. InitializeSdk therefore stays as internal plumbing, now defaulting to false and opted into by the framework integrations that own it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent 6438db5 commit d2e7281

25 files changed

Lines changed: 102 additions & 182 deletions

‎samples/Sentry.Samples.GenericHost/Program.cs‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,19 @@
77

88
builder.Logging.AddConfiguration(builder.Configuration);
99

10+
// Initialise the Sentry SDK. The logging integration added below only forwards log messages to Sentry.
11+
using var sentry = SentrySdk.Init(options =>
12+
{
1013
#if !SENTRY_DSN_DEFINED_IN_ENV
11-
// A DSN is required. You can set it here in code, via the SENTRY_DSN environment variable or in your
12-
// appsettings.json file.
13-
// See https://docs.sentry.io/platforms/dotnet/guides/aspnetcore/#configure
14-
builder.Logging.AddSentry(SamplesShared.Dsn);
15-
#else
16-
builder.Logging.AddSentry();
14+
// A DSN is required. You can set here in code, or you can set it in the SENTRY_DSN environment variable.
15+
// See https://docs.sentry.io/product/sentry-basics/dsn-explainer/
16+
options.Dsn = SamplesShared.Dsn;
1717
#endif
18+
// Send user name and machine name
19+
options.SendDefaultPii = true;
20+
});
21+
22+
builder.Logging.AddSentry();
1823

1924
builder.Services.AddHostedService<SampleHostedService>();
2025

‎samples/Sentry.Samples.GenericHost/appsettings.json‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,7 @@
1010
}
1111
},
1212
"Sentry": {
13-
//"Dsn": "TODO: Configure your DSN here and uncomment this line",
1413
"MinimumBreadcrumbLevel": "Debug",
15-
"MinimumEventLevel": "Warning",
16-
"SendDefaultPii": true // Send user name and machine name
14+
"MinimumEventLevel": "Warning"
1715
}
1816
}

‎samples/Sentry.Samples.ME.Logging/Program.cs‎

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,39 @@
11
using Microsoft.Extensions.Logging;
22
using Sentry.Extensions.Logging;
33

4-
using var loggerFactory = LoggerFactory.Create(builder =>
4+
// Initialise the Sentry SDK. The logging integration added below only forwards log messages to Sentry.
5+
using var sentry = SentrySdk.Init(options =>
56
{
6-
builder.AddConsole();
7-
builder.AddSentry(options =>
8-
{
97
#if !SENTRY_DSN_DEFINED_IN_ENV
10-
// A DSN is required. You can set here in code, or you can set it in the SENTRY_DSN environment variable.
11-
// See https://docs.sentry.io/product/sentry-basics/dsn-explainer/
12-
options.Dsn = SamplesShared.Dsn;
8+
// A DSN is required. You can set here in code, or you can set it in the SENTRY_DSN environment variable.
9+
// See https://docs.sentry.io/product/sentry-basics/dsn-explainer/
10+
options.Dsn = SamplesShared.Dsn;
1311
#endif
1412

15-
// Set to true to SDK debugging to see the internal messages through the logging library.
16-
options.Debug = false;
17-
// Configure the level of Sentry internal logging
18-
options.DiagnosticLevel = SentryLevel.Debug;
13+
// Set to true to SDK debugging to see the internal messages through the logging library.
14+
options.Debug = false;
15+
// Configure the level of Sentry internal logging
16+
options.DiagnosticLevel = SentryLevel.Debug;
1917

20-
options.MaxBreadcrumbs = 150; // Increasing from default 100
21-
options.Release = "e386dfd"; // If not set here, SDK looks for it on main assembly's AssemblyInformationalVersion and AssemblyVersion
18+
options.MaxBreadcrumbs = 150; // Increasing from default 100
19+
options.Release = "e386dfd"; // If not set here, SDK looks for it on main assembly's AssemblyInformationalVersion and AssemblyVersion
20+
21+
options.SetBeforeSendLog(static log =>
22+
{
23+
log.SetAttribute("attribute-key", "attribute-value");
24+
return log;
25+
});
26+
});
2227

28+
using var loggerFactory = LoggerFactory.Create(builder =>
29+
{
30+
builder.AddConsole();
31+
builder.AddSentry(options =>
32+
{
2333
// Optionally configure options: The default values are:
2434
options.MinimumBreadcrumbLevel = LogLevel.Information; // It requires at least this level to store breadcrumb
2535
options.MinimumEventLevel = LogLevel.Error; // This level or above will result in event sent to Sentry
2636

27-
options.SetBeforeSendLog(static log =>
28-
{
29-
log.SetAttribute("attribute-key", "attribute-value");
30-
return log;
31-
});
32-
3337
// Don't keep as a breadcrumb or send events for messages of level less than Critical with exception of type DivideByZeroException
3438
options.AddLogEntryFilter((_, level, _, exception) => level < LogLevel.Critical && exception is DivideByZeroException);
3539

@@ -86,8 +90,6 @@
8690
Dependency.Work("8 - This unhandled exception is captured and includes Scope (A, B) and crumbs: (2, 4, 5) and event (3) ");
8791
}
8892

89-
// Disposing the LoggerFactory will close the SDK since it was initialized through
90-
// the integration while calling .Init()
9193

9294
internal static class Dependency
9395
{

‎samples/Sentry.Samples.OpenTelemetry.AzureFunctions/Program.cs‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,16 @@
1414
var dsn = SamplesShared.Dsn;
1515
#endif
1616

17+
// Initialise the Sentry SDK. The logging integration added below only forwards log messages to Sentry.
18+
using var sentry = SentrySdk.Init(options =>
19+
{
20+
options.Dsn = dsn;
21+
options.TracesSampleRate = 1.0;
22+
options.UseOtlp(); // <-- Configure Sentry to use open telemetry
23+
options.DisableSentryHttpMessageHandler = true; // So Sentry doesn't also create spans for outbound HTTP requests
24+
options.Debug = true;
25+
});
26+
1727
var host = new HostBuilder()
1828
.ConfigureFunctionsWorkerDefaults()
1929
.ConfigureServices(services =>
@@ -25,17 +35,7 @@
2535
.AddHttpClientInstrumentation(); // From OpenTelemetry.Instrumentation.Http... adds automatic tracing for outgoing HTTP requests
2636
});
2737
})
28-
.ConfigureLogging(logging =>
29-
{
30-
logging.AddSentry(options =>
31-
{
32-
options.Dsn = dsn;
33-
options.TracesSampleRate = 1.0;
34-
options.UseOtlp(); // <-- Configure Sentry to use open telemetry
35-
options.DisableSentryHttpMessageHandler = true; // So Sentry doesn't also create spans for outbound HTTP requests
36-
options.Debug = true;
37-
});
38-
})
38+
.ConfigureLogging(logging => logging.AddSentry())
3939
.Build();
4040

4141
await host.RunAsync();

‎src/Sentry.AspNetCore.Blazor.WebAssembly/WebAssemblyHostBuilderExtensions.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,5 +46,10 @@ public static WebAssemblyHostBuilder UseSentry(this WebAssemblyHostBuilder build
4646
/// </summary>
4747
public class SentryBlazorOptions : SentryLoggingOptions
4848
{
49+
/// <summary>
50+
/// Creates a new instance of <see cref="SentryBlazorOptions"/>.
51+
/// </summary>
52+
public SentryBlazorOptions() => InitializeSdk = true;
53+
4954
// Awesome Blazor specific options go here
5055
}

‎src/Sentry.AspNetCore/SentryAspNetCoreOptions.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,8 @@ public SentryAspNetCoreOptions()
108108
{
109109
// Don't report Environment.UserName as the user.
110110
IsEnvironmentUser = false;
111+
112+
InitializeSdk = true;
111113
}
112114

113115
internal void SetEnvironment(IWebHostEnvironment hostingEnvironment)

‎src/Sentry.Extensions.Logging/BindableSentryLoggingOptions.cs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,11 @@ internal class BindableSentryLoggingOptions : BindableSentryOptions
77
{
88
public LogLevel? MinimumBreadcrumbLevel { get; set; }
99
public LogLevel? MinimumEventLevel { get; set; }
10-
public bool? InitializeSdk { get; set; }
1110

1211
public void ApplyTo(SentryLoggingOptions options)
1312
{
1413
base.ApplyTo(options);
1514
options.MinimumBreadcrumbLevel = MinimumBreadcrumbLevel ?? options.MinimumBreadcrumbLevel;
1615
options.MinimumEventLevel = MinimumEventLevel ?? options.MinimumEventLevel;
17-
options.InitializeSdk = InitializeSdk ?? options.InitializeSdk;
1816
}
1917
}

‎src/Sentry.Extensions.Logging/LoggingBuilderExtensions.cs‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,6 @@ public static class LoggingBuilderExtensions
2121
public static ILoggingBuilder AddSentry(this ILoggingBuilder builder)
2222
=> builder.AddSentry((Action<SentryLoggingOptions>?)null);
2323

24-
/// <summary>
25-
/// Adds the Sentry logging integration.
26-
/// </summary>
27-
/// <param name="builder">The builder.</param>
28-
/// <param name="dsn">The DSN.</param>
29-
public static ILoggingBuilder AddSentry(this ILoggingBuilder builder, string dsn)
30-
=> builder.AddSentry(o => o.Dsn = dsn);
31-
3224
/// <summary>
3325
/// Adds the Sentry logging integration.
3426
/// </summary>

‎src/Sentry.Extensions.Logging/SentryLoggerFactoryExtensions.cs‎

Lines changed: 3 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ public static class SentryLoggerFactoryExtensions
1717
/// Adds the Sentry logging integration.
1818
/// </summary>
1919
/// <remarks>
20-
/// This method does not need to be called when calling `UseSentry` with ASP.NET Core
21-
/// since that integrates with the logging framework automatically.
20+
/// This method does not initialize Sentry. Initialize it separately, with <see cref="SentrySdk.Init(Action{SentryOptions})"/>
21+
/// or a framework integration such as <c>UseSentry</c>.
2222
/// </remarks>
2323
/// <param name="factory">The factory.</param>
2424
/// <param name="optionsConfiguration">The options configuration.</param>
@@ -30,34 +30,7 @@ public static ILoggerFactory AddSentry(
3030

3131
optionsConfiguration?.Invoke(options);
3232

33-
if (options.DiagnosticLogger == null)
34-
{
35-
var logger = factory.CreateLogger<ISentryClient>();
36-
options.DiagnosticLogger = new MelDiagnosticLogger(logger, options.DiagnosticLevel);
37-
}
38-
39-
IHub hub;
40-
if (options.InitializeSdk)
41-
{
42-
if (SentrySdk.IsEnabled && options.Dsn is null)
43-
{
44-
options.LogWarning("Not calling Init from {0} because SDK is already enabled and no DSN was provided to the integration", nameof(SentryLoggerFactoryExtensions));
45-
hub = HubAdapter.Instance;
46-
}
47-
else
48-
{
49-
options.LogDebug("Initializing from {0} and swapping current Hub.", nameof(SentryLoggerFactoryExtensions));
50-
hub = SentrySdk.InitHub(options);
51-
SentrySdk.UseHub(hub);
52-
}
53-
}
54-
else
55-
{
56-
// Access to whatever the SentrySdk points to (disabled or initialized via SentrySdk.Init)
57-
hub = HubAdapter.Instance;
58-
}
59-
60-
factory.AddProvider(new SentryLoggerProvider(hub, SystemClock.Clock, options));
33+
factory.AddProvider(new SentryLoggerProvider(HubAdapter.Instance, SystemClock.Clock, options));
6134
return factory;
6235
}
6336
}

‎src/Sentry.Extensions.Logging/SentryLoggingOptions.cs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,17 @@ public class SentryLoggingOptions : SentryOptions
3030
/// </value>
3131
public LogLevel MinimumEventLevel { get; set; } = LogLevel.Error;
3232

33-
/// <summary>
34-
/// Whether to initialize this SDK through this integration
35-
/// </summary>
36-
public bool InitializeSdk { get; set; } = true;
37-
3833
/// <summary>
3934
/// Add a callback to configure the scope upon SDK initialization
4035
/// </summary>
4136
/// <param name="action">The function to invoke when initializing the SDK</param>
4237
public void ConfigureScope(Action<Scope> action) => ConfigureScopeCallbacks = ConfigureScopeCallbacks.Concat(new[] { action }).ToArray();
4338

39+
/// <summary>
40+
/// Whether the integration owning these options initializes the SDK
41+
/// </summary>
42+
internal bool InitializeSdk { get; set; }
43+
4444
/// <summary>
4545
/// Log entry filters
4646
/// </summary>

0 commit comments

Comments
 (0)