Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add IHostBuilder support #1015

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
91 changes: 55 additions & 36 deletions samples/Sentry.Samples.AspNetCore.Basic/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Sentry.AspNetCore;

namespace Sentry.Samples.AspNetCore.Basic
Expand All @@ -14,61 +15,79 @@ public class Program
public static void Main(string[] args)
{
BuildWebHost(args).Run();
// or
//BuildHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)

// Add Sentry integration
// In this example, DSN and Release are set via environment variable:
// See: Properties/launchSettings.json
.UseSentry()
// It can also be defined via configuration (including appsettings.json)
// or coded explicitly, via parameter like:
// .UseSentry("dsn") or .UseSentry(o => o.Dsn = ""; o.Release = "1.0"; ...)

// The App:
.Configure(app =>
{
// An example ASP.NET Core middleware that throws an
// exception when serving a request to path: /throw
app.UseRouting();
.Configure(ConfigureApp)
.Build();

// Enable Sentry performance monitoring
app.UseSentryTracing();
public static IHost BuildHost(string[] args) =>
Host.CreateDefaultBuilder(args)
// Add Sentry integration
// In this example, DSN and Release are set via environment variable:
// See: Properties/launchSettings.json
.UseSentry()
// It can also be defined via configuration (including appsettings.json)
// or coded explicitly, via parameter like:
// .UseSentry("dsn") or .UseSentry(o => o.Dsn = ""; o.Release = "1.0"; ...)
.ConfigureWebHost(webBuilder =>
{
// Note that it's NOT needed to also call UseSentry here. That's because it's already hooked through IHostBuilder
webBuilder.Configure(ConfigureApp);
})
.Build();

app.UseEndpoints(endpoints =>
{
// Reported events will be grouped by route pattern
endpoints.MapGet("/throw/{message?}", context =>
{
var exceptionMessage = context.GetRouteValue("message") as string;
private static void ConfigureApp(IApplicationBuilder app)
{
// An example ASP.NET Core middleware that throws an
// exception when serving a request to path: /throw
app.UseRouting();

var log = context.RequestServices.GetRequiredService<ILoggerFactory>()
.CreateLogger<Program>();
// Enable Sentry performance monitoring
app.UseSentryTracing();

log.LogInformation("Handling some request...");
app.UseEndpoints(endpoints =>
{
// Reported events will be grouped by route pattern
endpoints.MapGet("/throw/{message?}", context =>
{
var exceptionMessage = context.GetRouteValue("message") as string;

var hub = context.RequestServices.GetRequiredService<IHub>();
hub.ConfigureScope(s =>
{
// More data can be added to the scope like this:
s.SetTag("Sample", "ASP.NET Core"); // indexed by Sentry
s.SetExtra("Extra!", "Some extra information");
});
var log = context.RequestServices.GetRequiredService<ILoggerFactory>()
.CreateLogger<Program>();

log.LogInformation("Logging info...");
log.LogWarning("Logging some warning!");
log.LogInformation("Handling some request...");

// The following exception will be captured by the SDK and the event
// will include the Log messages and any custom scope modifications
// as exemplified above.
throw new Exception(
exceptionMessage ?? "An exception thrown from the ASP.NET Core pipeline"
);
});
var hub = context.RequestServices.GetRequiredService<IHub>();
hub.ConfigureScope(s =>
{
// More data can be added to the scope like this:
s.SetTag("Sample", "ASP.NET Core"); // indexed by Sentry
s.SetExtra("Extra!", "Some extra information");
});
})
.Build();

log.LogInformation("Logging info...");
log.LogWarning("Logging some warning!");

// The following exception will be captured by the SDK and the event
// will include the Log messages and any custom scope modifications
// as exemplified above.
throw new Exception(
exceptionMessage ?? "An exception thrown from the ASP.NET Core pipeline"
);
});
});
}
}
}
28 changes: 14 additions & 14 deletions samples/Sentry.Samples.AspNetCore5.Mvc/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseSentry(o =>
webBuilder.UseStartup<Startup>();
})
.UseSentry(o =>
{
o.Debug = true;
o.MaxRequestBodySize = RequestSize.Always;
o.Dsn = "https://[email protected]/5428537";
o.TracesSampler = ctx =>
{
o.Debug = true;
o.MaxRequestBodySize = RequestSize.Always;
o.Dsn = "https://[email protected]/5428537";
o.TracesSampler = ctx =>
if (string.Equals(ctx.TryGetHttpRoute(), "/Home/Privacy", StringComparison.Ordinal))
{
if (string.Equals(ctx.TryGetHttpRoute(), "/Home/Privacy", StringComparison.Ordinal))
{
// Collect fewer traces for this page
return 0.3;
}
// Collect fewer traces for this page
return 0.3;
}

return 1;
};
});
webBuilder.UseStartup<Startup>();
return 1;
};
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Sentry.Samples.AspNetCore3.Mvc": {
"Sentry.Samples.AspNetCore5.Mvc": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
Expand All @@ -24,4 +24,4 @@
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
}
8 changes: 2 additions & 6 deletions samples/Sentry.Samples.GenericHost/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,8 @@ public static Task Main()
c.AddJsonFile("appsettings.json", optional: false);
})
.ConfigureServices((c, s) => { s.AddHostedService<SampleHostedService>(); })
.ConfigureLogging((c, l) =>
{
l.AddConfiguration(c.Configuration);
l.AddConsole();
l.AddSentry();
})
.ConfigureLogging(b => b.AddConsole())
.UseSentry()
Copy link
Member

Choose a reason for hiding this comment

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

Very nice!

.UseConsoleLifetime()
.Build()
.RunAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../../src/Sentry.Extensions.Logging/Sentry.Extensions.Logging.csproj" />
<ProjectReference Include="../../src/Sentry.AspNetCore/Sentry.AspNetCore.csproj" />
Copy link
Member

Choose a reason for hiding this comment

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

Do we need to change the dependency to ASP.NET Core integration? The new types are all on the S.E.L, right?

Suggested change
<ProjectReference Include="../../src/Sentry.AspNetCore/Sentry.AspNetCore.csproj" />
<ProjectReference Include="../../src/Sentry.Extensions.Logging/Sentry.Extensions.Logging.csproj" />

Copy link
Author

Choose a reason for hiding this comment

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

New types are not on S.E.L. right now, see comment below

</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.8" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.1.1" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.ComponentModel;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Sentry.AspNetCore;
using Sentry.Extensibility;
Expand All @@ -20,17 +22,55 @@ internal static class ServiceCollectionExtensions
/// <returns></returns>
public static ISentryBuilder AddSentry(this IServiceCollection services)
{
services.AddSingleton<ISentryEventProcessor, AspNetCoreEventProcessor>();
if (!services.IsRegistered<ISentryEventProcessor, AspNetCoreEventProcessor>())
{
services.AddSingleton<ISentryEventProcessor, AspNetCoreEventProcessor>();
}

services.TryAddSingleton<IUserFactory, DefaultUserFactory>();

services
.AddSingleton<IRequestPayloadExtractor, FormRequestPayloadExtractor>()
// Last
.AddSingleton<IRequestPayloadExtractor, DefaultRequestPayloadExtractor>();

if (!services.IsRegistered<IRequestPayloadExtractor, FormRequestPayloadExtractor>())
{
services.AddSingleton<IRequestPayloadExtractor, FormRequestPayloadExtractor>();
}

// Last
if (!services.IsRegistered<IRequestPayloadExtractor, DefaultRequestPayloadExtractor>())
{
services.AddSingleton<IRequestPayloadExtractor, DefaultRequestPayloadExtractor>();
}

services.AddSentry<SentryAspNetCoreOptions>();

return new SentryAspNetCoreBuilder(services);
}

/// <summary>
/// Checks if a specific ServiceDescriptor was previously registered in the <see cref="IServiceCollection"/>
/// </summary>
/// <param name="serviceCollection"></param>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TU"></typeparam>
/// <returns></returns>
internal static bool IsRegistered<T, TU>(this IServiceCollection serviceCollection)
{
return serviceCollection.Any(x => x.ImplementationType == typeof(T) && x.ServiceType == typeof(TU));
}

/// <summary>
/// Adds Sentry's StartupFilter to the <see cref="IServiceCollection"/>
/// </summary>
/// <param name="serviceCollection"></param>
/// <returns></returns>
internal static IServiceCollection AddSentryStartupFilter(this IServiceCollection serviceCollection)
{
if (!serviceCollection.IsRegistered<IStartupFilter, SentryStartupFilter>())
{
_ = serviceCollection.AddTransient<IStartupFilter, SentryStartupFilter>();
}

return serviceCollection;
}
}
}
1 change: 1 addition & 0 deletions src/Sentry.AspNetCore/Sentry.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.1.0" />
Expand Down
7 changes: 3 additions & 4 deletions src/Sentry.AspNetCore/SentryAspNetCoreOptionsSetup.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
using System;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
using Sentry.Extensions.Logging;
using Sentry.Internal;
#if NETSTANDARD2_0
using Microsoft.AspNetCore.Hosting;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
using IHostingEnvironment = Microsoft.Extensions.Hosting.IHostingEnvironment;
#else
using Microsoft.Extensions.Hosting;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IWebHostEnvironment;
using IHostingEnvironment = Microsoft.Extensions.Hosting.IHostEnvironment;
#endif

namespace Sentry.AspNetCore
Expand Down
93 changes: 93 additions & 0 deletions src/Sentry.AspNetCore/SentryHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System;
using System.ComponentModel;
using Microsoft.Extensions.DependencyInjection;
using Sentry.AspNetCore;

// ReSharper disable once CheckNamespace
namespace Microsoft.Extensions.Hosting
{
/// <summary>
/// Extension methods to <see cref="IHostBuilder"/>
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class SentryHostBuilderExtensions
{
/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns></returns>
public static IHostBuilder UseSentry(this IHostBuilder builder)
Copy link
Member

Choose a reason for hiding this comment

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

IHostBuilder lives in Microsoft.Extensions.Hosting so this could be added to Sentry.Extensions.Logging.

Copy link
Author

Choose a reason for hiding this comment

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

I would've personally kept it in the asp.net core part, as it is the replacement of WebHostBuilder in the future.
Would you like me to move it ?

=> builder.UseSentry((Action<SentryAspNetCoreOptions>?)null);

/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="dsn">The DSN.</param>
/// <returns></returns>
public static IHostBuilder UseSentry(this IHostBuilder builder, string dsn)
=> builder.UseSentry(o => o.Dsn = dsn);

/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureOptions">The configure options.</param>
/// <returns></returns>
public static IHostBuilder UseSentry(
this IHostBuilder builder,
Action<SentryAspNetCoreOptions>? configureOptions)
=> builder.UseSentry((_, options) => configureOptions?.Invoke(options));

/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureOptions">The configure options.</param>
/// <returns></returns>
public static IHostBuilder UseSentry(
this IHostBuilder builder,
Action<HostBuilderContext, SentryAspNetCoreOptions>? configureOptions)
=> builder.UseSentry((context, sentryBuilder) =>
sentryBuilder.AddSentryOptions(options => configureOptions?.Invoke(context, options)));

/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureSentry">The Sentry builder.</param>
/// <returns></returns>
public static IHostBuilder UseSentry(
this IHostBuilder builder,
Action<ISentryBuilder>? configureSentry) =>
builder.UseSentry((_, sentryBuilder) => configureSentry?.Invoke(sentryBuilder));

/// <summary>
/// Uses Sentry integration.
/// </summary>
/// <param name="builder">The builder.</param>
/// <param name="configureSentry">The Sentry builder.</param>
/// <returns></returns>
public static IHostBuilder UseSentry(
this IHostBuilder builder,
Action<HostBuilderContext, ISentryBuilder>? configureSentry)
{
// The earliest we can hook the SDK initialization code with the framework
// Initialization happens at a later time depending if the default MEL backend is enabled or not.
// In case the logging backend was replaced, init happens later, at the StartupFilter
_ = builder.ConfigureLogging((context, logging) =>
bruno-garcia marked this conversation as resolved.
Show resolved Hide resolved
{
var sentryBuilder = logging.AddSentry(context.Configuration);
configureSentry?.Invoke(context, sentryBuilder);
});

_ = builder.ConfigureServices( s=>
{
_ = s.AddSentryStartupFilter();
});

return builder;
}
}
}
Loading