Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -63,6 +64,7 @@ internal static ILoggingBuilder AddSentryBlazor(
SystemClock.Clock,
c.GetRequiredService<IOptions<SentryBlazorOptions>>().Value.Logging));
logging.Services.AddSingleton<ILoggerProvider>(c => new SentryStructuredLoggerProvider(c.GetRequiredService<IHub>()));
logging.Services.TryAddSingleton<HostLoggerProvidersMarker>();
logging.Services.AddSentry<SentryBlazorOptions>();

logging.AddFilter<SentryLoggerProvider>(_ => true);
Expand Down
2 changes: 2 additions & 0 deletions src/Sentry.AspNetCore/SentryWebHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
Expand Down Expand Up @@ -93,6 +94,7 @@ public static IWebHostBuilder UseSentry(
);
_ = logging.Services.AddSingleton<ILoggerProvider, SentryAspNetCoreLoggerProvider>();
_ = logging.Services.AddSingleton<ILoggerProvider, SentryAspNetCoreStructuredLoggerProvider>();
logging.Services.TryAddSingleton<HostLoggerProvidersMarker>();

// Add a delegate rule in order to ignore Configuration like "appsettings.json" and "appsettings.{HostEnvironment}.json"
_ = logging.AddFilter<SentryAspNetCoreLoggerProvider>(static (string? categoryName, LogLevel logLevel) =>
Expand Down
3 changes: 3 additions & 0 deletions src/Sentry.Extensions.Logging/HostLoggerProvidersMarker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace Sentry.Extensions.Logging;

internal sealed class HostLoggerProvidersMarker;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note, not blocking: builder.Logging.ClearProviders() removes the host's providers but leaves this marker. So UseSentry, then ClearProviders(), then Logging.AddSentry() ends up with only the two NullLoggerProviders: no events or breadcrumbs from ILogger, and a warning that the call is redundant. That order works on version7 today, but neither our docs nor our samples use it, and calling ClearProviders() before UseSentry avoids it, so it's fine to leave. If you want to cover it, the marker could hold the host provider's ServiceDescriptor and check services.Contains(descriptor) when the Logging.AddSentry() factories run.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is enough of a weird outliier situation that we can ignore it... there's only so much we can do to prevent users from shooting themselves in the foot with a gun.

24 changes: 22 additions & 2 deletions src/Sentry.Extensions.Logging/LoggingBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
using Sentry;
using Sentry.Extensibility;
using Sentry.Extensions.Logging;
using Sentry.Extensions.Logging.Extensions.DependencyInjection;

Expand All @@ -17,6 +20,9 @@ public static class LoggingBuilderExtensions
/// <summary>
/// Adds the Sentry logging integration.
/// </summary>
/// <remarks>
/// Has no effect in an app that calls <c>UseSentry</c>, which already adds the logging integration.
/// </remarks>
/// <param name="builder">The builder.</param>
public static ILoggingBuilder AddSentry(this ILoggingBuilder builder)
=> builder.AddSentry((Action<SentryLoggingOptions>?)null);
Expand All @@ -35,6 +41,9 @@ public static ILoggingBuilder AddSentry(this ILoggingBuilder builder, string dsn
/// <summary>
/// Adds the Sentry logging integration.
/// </summary>
/// <remarks>
/// Has no effect in an app that calls <c>UseSentry</c>, which already adds the logging integration.
/// </remarks>
/// <param name="builder">The builder.</param>
/// <param name="optionsConfiguration">The options configuration.</param>
public static ILoggingBuilder AddSentry(this ILoggingBuilder builder, Action<SentryLoggingOptions>? optionsConfiguration)
Expand All @@ -47,8 +56,19 @@ public static ILoggingBuilder AddSentry(this ILoggingBuilder builder, Action<Sen
}

builder.Services.AddSingleton<IConfigureOptions<SentryLoggingOptions>, SentryLoggingOptionsSetup>();
builder.Services.AddSingleton<ILoggerProvider, SentryLoggerProvider>();
builder.Services.AddSingleton<ILoggerProvider, SentryStructuredLoggerProvider>();
builder.Services.AddSingleton<ILoggerProvider>(c =>
{
if (c.GetService<HostLoggerProvidersMarker>() is null)
{
return new SentryLoggerProvider(c.GetRequiredService<IOptions<SentryLoggingOptions>>(), c.GetRequiredService<IHub>());
}

c.GetRequiredService<IHub>().GetSentryOptions()?.LogWarning(SentryLoggingOptions.RedundantWithHostIntegration);
return NullLoggerProvider.Instance;
});
builder.Services.AddSingleton<ILoggerProvider>(c => c.GetService<HostLoggerProvidersMarker>() is null
? new SentryStructuredLoggerProvider(c.GetRequiredService<IHub>())
: NullLoggerProvider.Instance);
builder.Services.AddSentryHub();

// All logs should flow to the SentryLogger, regardless of level.
Expand Down
5 changes: 5 additions & 0 deletions src/Sentry.Extensions.Logging/SentryLoggingOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ public class SentryLoggingOptions
"supplied to it. Initialize Sentry with SentrySdk.Init (or UseSentry via one of the integrations), and " +
"remove 'Dsn', 'InitializeSdk' and any other core SDK settings from the logging configuration.";

internal const string RedundantWithHostIntegration =
"Logging.AddSentry() is redundant because the host integration, such as UseSentry, already adds Sentry's " +
"logger providers. Its providers are disabled and its options ignored: remove the call and configure " +
"logging through the host's Sentry options.";

/// <summary>
/// Not supported. The logging integration no longer initializes the SDK.
/// </summary>
Expand Down
2 changes: 2 additions & 0 deletions src/Sentry.Google.Cloud.Functions/SentryStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Sentry;
Expand Down Expand Up @@ -63,6 +64,7 @@ public override void ConfigureLogging(WebHostBuilderContext context, ILoggingBui

logging.Services.AddSingleton<ILoggerProvider, SentryAspNetCoreLoggerProvider>();
logging.Services.AddSingleton<ILoggerProvider, SentryAspNetCoreStructuredLoggerProvider>();
logging.Services.TryAddSingleton<HostLoggerProvidersMarker>();

// Add a delegate rule in order to ignore Configuration like "appsettings.json" and "appsettings.{HostEnvironment}.json"
logging.AddFilter<SentryAspNetCoreLoggerProvider>(static (string? categoryName, LogLevel logLevel) =>
Expand Down
2 changes: 2 additions & 0 deletions src/Sentry.Maui/SentryMauiAppBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.Extensions.Options;
using Microsoft.Maui.LifecycleEvents;
using Sentry.Extensibility;
using Sentry.Extensions.Logging;
using Sentry.Extensions.Logging.Extensions.DependencyInjection;
using Sentry.Maui;
using Sentry.Maui.Internal;
Expand Down Expand Up @@ -53,6 +54,7 @@ public static MauiAppBuilder UseSentry(this MauiAppBuilder builder,
services.AddLogging();
services.AddSingleton<ILoggerProvider, SentryMauiLoggerProvider>();
services.AddSingleton<ILoggerProvider, SentryMauiStructuredLoggerProvider>();
services.TryAddSingleton<HostLoggerProvidersMarker>();
services.AddSingleton<IMauiInitializeService, SentryMauiInitializer>();
services.AddSingleton<IConfigureOptions<SentryMauiOptions>, SentryMauiOptionsSetup>();
services.AddSingleton<Disposer>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace Sentry.AspNetCore.Blazor.WebAssembly.Tests;
public class WebAssemblyHostBuilderExtensionsTests : IDisposable
{
private readonly List<SentryEvent> _events = new();
private bool _alsoCallLoggingAddSentry;

public void Dispose() => SentrySdk.Close();

Expand All @@ -34,6 +35,10 @@ private ServiceProvider GetSut(
});
configureOptions(o);
}));
if (_alsoCallLoggingAddSentry)
{
services.AddLogging(logging => logging.AddSentry());
}
return services.BuildServiceProvider();
}

Expand Down Expand Up @@ -116,6 +121,28 @@ public void UseSentry_EnableLogsInConfiguration_SendsLogs()
logs.Should().ContainSingle().Which.Message.Should().Be("message");
}

[Fact]
public void UseSentry_WithLoggingAddSentry_CapturesEventOnce()
{
_alsoCallLoggingAddSentry = true;
using var provider = GetSut(_ => { });
var logger = provider.GetRequiredService<ILoggerFactory>().CreateLogger("test_category");

logger.LogError("message");

_events.Should().ContainSingle();
}

[Fact]
public void UseSentry_WithLoggingAddSentryAndEnableLogs_SendsLogOnce()
{
_alsoCallLoggingAddSentry = true;

var logs = LogInformation(o => o.EnableLogs = true);

logs.Should().ContainSingle();
}

private List<SentryLog> LogInformation(
Action<SentryBlazorOptions> configureOptions,
params (string Key, string Value)[] settings)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Sentry.Extensions.Logging;

Expand Down Expand Up @@ -99,6 +100,25 @@ public void UseSentry_Logging_AddLoggerProviders()
providers[1].Should().BeOfType<SentryAspNetCoreStructuredLoggerProvider>();
}

[Fact]
public void UseSentry_WithLoggingAddSentry_LoggingAddSentryProvidersDisabled()
{
Services.AddLogging(logging => logging.AddSentry());
WebHostBuilder.UseSentry((SentryAspNetCoreOptions options) =>
{
options.Dsn = Sentry.SentryConstants.DisableSdkDsnValue;
});
using var serviceProvider = Services.BuildServiceProvider();

var providers = serviceProvider.GetRequiredService<IEnumerable<ILoggerProvider>>();

providers.Select(p => p.GetType()).Should().Equal(
typeof(NullLoggerProvider),
typeof(NullLoggerProvider),
typeof(SentryAspNetCoreLoggerProvider),
typeof(SentryAspNetCoreStructuredLoggerProvider));
}

[Fact]
public void UseSentry_Logging_AddLoggerFilterRules()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Sentry.Extensions.Logging;

namespace Sentry.AspNetCore.Tests;

Expand All @@ -11,9 +12,13 @@ namespace Sentry.AspNetCore.Tests;
[Collection(nameof(SentrySdkCollection))]
public class UseSentryWithLoggingAddSentryTests : IDisposable
{
private readonly List<SentryEvent> _events = new();
private readonly List<SentryLog> _logs = new();
private readonly InMemoryDiagnosticLogger _diagnosticLogger = new();

public void Dispose() => SentrySdk.Close();

private static IHub BuildHub(bool useSentryFirst)
private WebApplication Build(bool useSentryFirst, bool enableLogs = false)
{
var builder = WebApplication.CreateBuilder();

Expand All @@ -23,6 +28,19 @@ void UseSentry() => builder.WebHost.UseSentry((SentryAspNetCoreOptions options)
options.BackgroundWorker = Substitute.For<IBackgroundWorker>();
options.AutoSessionTracking = false;
options.InitNativeSdks = false;
options.Debug = true;
options.DiagnosticLogger = _diagnosticLogger;
options.EnableLogs = enableLogs;
options.SetBeforeSend((e, _) =>
{
_events.Add(e);
return null;
});
options.SetBeforeSendLog(log =>
{
_logs.Add(log);
return null;
});
});

if (useSentryFirst)
Expand All @@ -36,14 +54,60 @@ void UseSentry() => builder.WebHost.UseSentry((SentryAspNetCoreOptions options)
UseSentry();
}

using var app = builder.Build();
return app.Services.GetRequiredService<IHub>();
return builder.Build();
}

private static ILogger CreateLogger(WebApplication app)
=> app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("test_category");

[Theory]
[InlineData(true)]
[InlineData(false)]
public void UseSentry_WithLoggingAddSentry_InitializesSdk(bool useSentryFirst)
=> Assert.True(BuildHub(useSentryFirst).IsEnabled);
{
using var app = Build(useSentryFirst);

Assert.True(app.Services.GetRequiredService<IHub>().IsEnabled);
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public void UseSentry_WithLoggingAddSentry_CapturesEventAndBreadcrumbOnce(bool useSentryFirst)
{
using var app = Build(useSentryFirst);
var logger = CreateLogger(app);

logger.LogInformation("breadcrumb");
logger.LogError("event");

_events.Should().ContainSingle()
.Which.Breadcrumbs.Should().ContainSingle(b => b.Message == "breadcrumb");
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public void UseSentry_WithLoggingAddSentryAndEnableLogs_SendsLogOnce(bool useSentryFirst)
{
using var app = Build(useSentryFirst, enableLogs: true);

CreateLogger(app).LogWarning("log");

_logs.Should().ContainSingle();
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public void UseSentry_WithLoggingAddSentry_WarnsCallIsRedundant(bool useSentryFirst)
{
using var app = Build(useSentryFirst);

_ = app.Services.GetRequiredService<ILoggerFactory>();

_diagnosticLogger.Entries.Should().ContainSingle(e =>
e.Level == SentryLevel.Warning && e.Message == SentryLoggingOptions.RedundantWithHostIntegration);
}
}
#endif
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;

namespace Sentry.Extensions.Logging.Tests;
Expand All @@ -24,6 +25,19 @@ public void AddSentry_LoggingBuilder_AddLoggerProviders()
providers[1].Should().BeOfType<SentryStructuredLoggerProvider>();
}

[Fact]
public void AddSentry_HostLoggerProvidersRegistered_AddsNullLoggerProviders()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<HostLoggerProvidersMarker>();
serviceCollection.AddLogging(builder => builder.AddSentry());
using var serviceProvider = serviceCollection.BuildServiceProvider();

var providers = serviceProvider.GetRequiredService<IEnumerable<ILoggerProvider>>();

providers.Should().HaveCount(2).And.AllBeOfType<NullLoggerProvider>();
}

[Fact]
public void AddSentry_LoggingBuilder_AddLoggerFilterRules()
{
Expand Down
23 changes: 23 additions & 0 deletions test/Sentry.Google.Cloud.Functions.Tests/SentryStartupTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Sentry.AspNetCore;

Expand Down Expand Up @@ -184,6 +185,28 @@ public void ConfigureLogging_Logging_AddLoggerProviders()
providers[1].Should().BeOfType<SentryAspNetCoreStructuredLoggerProvider>();
}

[Fact]
public void ConfigureLogging_WithLoggingAddSentry_LoggingAddSentryProvidersDisabled()
{
LoggingBuilder.Services.Configure<SentryAspNetCoreOptions>(options =>
{
options.Dsn = Sentry.SentryConstants.DisableSdkDsnValue;
});

var sut = new SentryStartup();
sut.ConfigureLogging(WebHostBuilderContext, LoggingBuilder);
LoggingBuilder.AddSentry();

using var serviceProvider = LoggingBuilder.Services.BuildServiceProvider();
var providers = serviceProvider.GetRequiredService<IEnumerable<ILoggerProvider>>();

providers.Select(p => p.GetType()).Should().Equal(
typeof(SentryAspNetCoreLoggerProvider),
typeof(SentryAspNetCoreStructuredLoggerProvider),
typeof(NullLoggerProvider),
typeof(NullLoggerProvider));
}

[Fact]
public void ConfigureLogging_Logging_AddLoggerFilterRules()
{
Expand Down
Loading