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
17 changes: 9 additions & 8 deletions src/Sentry.AspNetCore/SentryMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ namespace Sentry.AspNetCore
internal class SentryMiddleware
{
private readonly RequestDelegate _next;
private readonly IHub _sentry;
private readonly Func<IHub> _hubAccessor;
private readonly SentryAspNetCoreOptions _options;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ILogger<SentryMiddleware> _logger;
Expand All @@ -32,7 +32,7 @@ internal static readonly (string Name, string Version) NameAndVersion
/// Initializes a new instance of the <see cref="SentryMiddleware"/> class.
/// </summary>
/// <param name="next">The next.</param>
/// <param name="sentry">The sentry.</param>
/// <param name="hubAccessor">The sentry Hub accessor.</param>
/// <param name="options">The options for this integration</param>
/// <param name="hostingEnvironment">The hosting environment.</param>
/// <param name="logger">Sentry logger.</param>
Expand All @@ -43,13 +43,13 @@ internal static readonly (string Name, string Version) NameAndVersion
/// </exception>
public SentryMiddleware(
RequestDelegate next,
IHub sentry,
Func<IHub> hubAccessor,
IOptions<SentryAspNetCoreOptions> options,
IHostingEnvironment hostingEnvironment,
ILogger<SentryMiddleware> logger)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_sentry = sentry ?? throw new ArgumentNullException(nameof(sentry));
_hubAccessor = hubAccessor ?? throw new ArgumentNullException(nameof(hubAccessor));
_options = options?.Value;
_hostingEnvironment = hostingEnvironment;
_logger = logger;
Expand All @@ -62,20 +62,21 @@ public SentryMiddleware(
/// <returns></returns>
public async Task InvokeAsync(HttpContext context)
{
if (!_sentry.IsEnabled)
var hub = _hubAccessor();
if (!hub.IsEnabled)
{
await _next(context).ConfigureAwait(false);
return;
}

using (_sentry.PushAndLockScope())
using (hub.PushAndLockScope())
{
if (_options?.IncludeRequestPayload == true)
{
context.Request.EnableRewind();
}

_sentry.ConfigureScope(scope =>
hub.ConfigureScope(scope =>
{
// At the point lots of stuff from the request are not yet filled
// Identity for example is added later on in the pipeline
Expand Down Expand Up @@ -110,7 +111,7 @@ void CaptureException(Exception e)

_logger?.LogTrace("Sending event '{SentryEvent}' to Sentry.", evt);

var id = _sentry.CaptureEvent(evt);
var id = hub.CaptureEvent(evt);

_logger?.LogInformation("Event '{id}' queued.", id);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
Expand Down Expand Up @@ -26,26 +27,22 @@ public static IServiceCollection AddSentry<TOptions>(this IServiceCollection ser

services.TryAddSingleton<OptionalHub>();

services.TryAddSingleton(c =>
services.TryAddTransient<ISentryClient>(c => c.GetRequiredService<IHub>());
services.TryAddTransient(c => c.GetRequiredService<Func<IHub>>()());

services.TryAddSingleton<Func<IHub>>(c =>
{
var options = c.GetRequiredService<IOptions<TOptions>>().Value;

IHub hub;
if (options.InitializeSdk)
{
hub = c.GetRequiredService<OptionalHub>();
}
else
{
// Access to whatever the SentrySdk points to (disabled or initialized via SentrySdk.Init)
hub = HubAdapter.Instance;
var hub = c.GetRequiredService<OptionalHub>();
SentrySdk.UseHub(hub);
}

return hub;
return () => HubAdapter.Instance;
});

services.TryAddSingleton<ISentryClient>(c => c.GetService<IHub>());

return services;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public static ILoggerFactory AddSentry(
if (options.InitializeSdk)
{
hub = new OptionalHub(options);
SentrySdk.UseHub(hub);
}
else
{
Expand Down
6 changes: 2 additions & 4 deletions src/Sentry/Internal/OptionalHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ namespace Sentry.Internal
internal class OptionalHub : IHub, IDisposable
{
private readonly IHub _hub;
private readonly IDisposable _disposable;

public bool IsEnabled => _hub.IsEnabled;

Expand All @@ -24,14 +23,13 @@ public OptionalHub(SentryOptions options)
if (!Dsn.TryParse(DsnLocator.FindDsnStringOrDisable(), out var dsn))
{
options.DiagnosticLogger?.LogWarning("Init was called but no DSN was provided nor located. Sentry SDK will be disabled.");
_hub = HubAdapter.Instance;
_hub = DisabledHub.Instance;
return;
}
options.Dsn = dsn;
}

_hub = new Hub(options);
_disposable = SentrySdk.UseHub(_hub);
}

public SentryId CaptureEvent(SentryEvent evt, Scope scope = null) => _hub.CaptureEvent(evt, scope);
Expand All @@ -50,6 +48,6 @@ public OptionalHub(SentryOptions options)

public SentryId LastEventId => _hub.LastEventId;

public void Dispose() => _disposable?.Dispose();
public void Dispose() => (_hub as IDisposable)?.Dispose();
}
}
4 changes: 3 additions & 1 deletion test/Sentry.AspNetCore.Tests/MiddlewareLoggerIntegration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ private class Fixture : IDisposable
{
public RequestDelegate RequestDelegate { get; set; } = _ => Task.CompletedTask;
public IHub Hub { get; set; }
public Func<IHub> HubAccessor { get; set; }
public ISentryClient Client { get; set; } = Substitute.For<ISentryClient>();
public ISystemClock Clock { get; set; } = Substitute.For<ISystemClock>();
public SentryAspNetCoreOptions Options { get; set; } = new SentryAspNetCoreOptions();
Expand All @@ -33,6 +34,7 @@ private class Fixture : IDisposable

public Fixture()
{
HubAccessor = () => Hub;
var loggingOptions = new SentryLoggingOptions
{
InitializeSdk = false,
Expand All @@ -51,7 +53,7 @@ public Fixture()
public SentryMiddleware GetSut()
=> new SentryMiddleware(
RequestDelegate,
Hub,
HubAccessor,
Microsoft.Extensions.Options.Options.Create(Options),
HostingEnvironment,
MiddlewareLogger);
Expand Down
10 changes: 6 additions & 4 deletions test/Sentry.AspNetCore.Tests/SentryMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ private class Fixture
{
public RequestDelegate RequestDelegate { get; set; } = _ => Task.CompletedTask;
public IHub Hub { get; set; } = Substitute.For<IHub>();
public Func<IHub> HubAccessor { get; set; }
public SentryAspNetCoreOptions Options { get; set; } = new SentryAspNetCoreOptions();
public IHostingEnvironment HostingEnvironment { get; set; } = Substitute.For<IHostingEnvironment>();
public ILogger<SentryMiddleware> Logger { get; set; } = Substitute.For<ILogger<SentryMiddleware>>();
Expand All @@ -27,14 +28,15 @@ private class Fixture

public Fixture()
{
HubAccessor = () => Hub;
Hub.IsEnabled.Returns(true);
HttpContext.Features.Returns(FeatureCollection);
}

public SentryMiddleware GetSut()
=> new SentryMiddleware(
RequestDelegate,
Hub,
HubAccessor,
Microsoft.Extensions.Options.Options.Create(Options),
HostingEnvironment,
Logger);
Expand Down Expand Up @@ -340,11 +342,11 @@ public void Ctor_NullRequestDelegate_ThrowsArgumentNullException()
}

[Fact]
public void Ctor_NullHub_ThrowsArgumentNullException()
public void Ctor_NullHubAccessor_ThrowsArgumentNullException()
{
_fixture.Hub = null;
_fixture.HubAccessor = null;
var ex = Assert.Throws<ArgumentNullException>(() => _fixture.GetSut());
Assert.Equal("sentry", ex.ParamName);
Assert.Equal("hubAccessor", ex.ParamName);
}

[Fact]
Expand Down