Skip to content

Commit 984a392

Browse files
authored
Add net8.0 support to sample projects (#3464)
1 parent 5710136 commit 984a392

File tree

7 files changed

+127
-171
lines changed

7 files changed

+127
-171
lines changed
Lines changed: 37 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,48 @@
1-
using Microsoft.AspNetCore;
1+
var builder = WebApplication.CreateBuilder(args);
22

3-
namespace Sentry.Samples.AspNetCore.Basic;
4-
5-
public class Program
3+
builder.WebHost.UseSentry(o =>
64
{
7-
public static void Main(string[] args)
8-
{
9-
BuildWebHost(args).Run();
10-
}
11-
12-
public static IWebHost BuildWebHost(string[] args) =>
13-
WebHost.CreateDefaultBuilder(args)
14-
15-
.UseSentry(o =>
16-
{
17-
// A DSN is required. You can set it here, or in configuration, or in an environment variable.
18-
o.Dsn = "https://[email protected]/5428537";
5+
// A DSN is required. You can set it here, or in configuration, or in an environment variable.
6+
o.Dsn = "https://[email protected]/5428537";
197

20-
// Enable Sentry performance monitoring
21-
o.TracesSampleRate = 1.0;
8+
// Enable Sentry performance monitoring
9+
o.TracesSampleRate = 1.0;
2210

2311
#if DEBUG
24-
// Log debug information about the Sentry SDK
25-
o.Debug = true;
12+
// Log debug information about the Sentry SDK
13+
o.Debug = true;
2614
#endif
27-
})
15+
});
2816

29-
// The App:
30-
.Configure(app =>
31-
{
32-
app.UseRouting();
17+
var app = builder.Build();
3318

34-
// An example ASP.NET Core middleware that throws an
35-
// exception when serving a request to path: /throw
36-
app.UseEndpoints(endpoints =>
37-
{
38-
// Reported events will be grouped by route pattern
39-
endpoints.MapGet("/throw/{message?}", context =>
40-
{
41-
var exceptionMessage = context.GetRouteValue("message") as string;
42-
43-
var log = context.RequestServices.GetRequiredService<ILoggerFactory>()
44-
.CreateLogger<Program>();
45-
46-
log.LogInformation("Handling some request...");
19+
// An example ASP.NET Core middleware that throws an
20+
// exception when serving a request to path: /throw
21+
app.MapGet("/throw/{message?}", context =>
22+
{
23+
var exceptionMessage = context.GetRouteValue("message") as string;
4724

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

56-
log.LogInformation("Logging info...");
57-
log.LogWarning("Logging some warning!");
28+
log.LogInformation("Handling some request...");
5829

59-
// The following exception will be captured by the SDK and the event
60-
// will include the Log messages and any custom scope modifications
61-
// as exemplified above.
62-
throw new Exception(
63-
exceptionMessage ?? "An exception thrown from the ASP.NET Core pipeline");
64-
});
65-
});
66-
})
67-
.Build();
68-
}
30+
var hub = context.RequestServices.GetRequiredService<IHub>();
31+
hub.ConfigureScope(s =>
32+
{
33+
// More data can be added to the scope like this:
34+
s.SetTag("Sample", "ASP.NET Core"); // indexed by Sentry
35+
s.SetExtra("Extra!", "Some extra information");
36+
});
37+
38+
log.LogInformation("Logging info...");
39+
log.LogWarning("Logging some warning!");
40+
41+
// The following exception will be captured by the SDK and the event
42+
// will include the Log messages and any custom scope modifications
43+
// as exemplified above.
44+
throw new Exception(
45+
exceptionMessage ?? "An exception thrown from the ASP.NET Core pipeline");
46+
});
47+
48+
app.Run();

samples/Sentry.Samples.AspNetCore.Basic/Sentry.Samples.AspNetCore.Basic.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<TargetFramework>net6.0</TargetFramework>
4+
<TargetFramework>net8.0</TargetFramework>
55
</PropertyGroup>
66

77
<ItemGroup>
Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,13 @@
1-
using Microsoft.Extensions.Configuration;
21
using Microsoft.Extensions.DependencyInjection;
32
using Microsoft.Extensions.Hosting;
43
using Microsoft.Extensions.Logging;
4+
using Sentry.Samples.GenericHost;
55

6-
await Host.CreateDefaultBuilder()
7-
.ConfigureHostConfiguration(c =>
8-
{
9-
c.SetBasePath(Directory.GetCurrentDirectory());
10-
c.AddJsonFile("appsettings.json", optional: false);
11-
})
12-
.ConfigureServices((_, s) => s.AddHostedService<SampleHostedService>())
13-
.ConfigureLogging((c, l) =>
14-
{
15-
l.AddConfiguration(c.Configuration);
16-
l.AddConsole();
17-
l.AddSentry();
18-
})
19-
.UseConsoleLifetime()
20-
.Build()
21-
.RunAsync();
6+
var builder = Host.CreateApplicationBuilder();
7+
8+
builder.Logging.AddConfiguration(builder.Configuration);
9+
builder.Logging.AddSentry();
10+
11+
builder.Services.AddHostedService<SampleHostedService>();
12+
13+
await builder.Build().RunAsync();
Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,21 @@
11
using Microsoft.Extensions.Hosting;
22
using Microsoft.Extensions.Logging;
33

4-
internal class SampleHostedService : IHostedService
5-
{
6-
private readonly IHub _hub;
7-
private readonly ILogger _logger;
8-
9-
public SampleHostedService(IHub hub, ILogger<SampleHostedService> logger)
10-
{
11-
_hub = hub;
12-
_logger = logger;
13-
}
4+
namespace Sentry.Samples.GenericHost;
145

6+
internal class SampleHostedService(IHub hub, ILogger<SampleHostedService> logger) : IHostedService
7+
{
158
public Task StartAsync(CancellationToken cancellationToken)
169
{
1710
// Logging integration by default keeps informational logs as Breadcrumb
18-
_logger.LogInformation("Starting sample hosted service. This goes as a breadcrumb");
11+
logger.LogInformation("Starting sample hosted service. This goes as a breadcrumb");
1912
// You can also add breadcrumb directly through Sentry.Hub:
20-
_hub.AddBreadcrumb("Breadcrumb added directly to Sentry Hub")
21-
;
13+
hub.AddBreadcrumb("Breadcrumb added directly to Sentry Hub");
2214
// Hub allows total control of the scope
23-
_hub.ConfigureScope(s => s.SetTag("Worker", nameof(SampleHostedService)));
15+
hub.ConfigureScope(s => s.SetTag("Worker", nameof(SampleHostedService)));
2416

25-
// By default Error and Critical log messages are sent to sentry as events
26-
_logger.LogError("An event sent to sentry.");
17+
// By default, Error and Critical log messages are sent to sentry as events
18+
logger.LogError("An event sent to sentry.");
2719

2820
return Task.Run(() =>
2921
{
@@ -35,14 +27,14 @@ public Task StartAsync(CancellationToken cancellationToken)
3527
catch (Exception e)
3628
{
3729
// Direct control of capturing errors with Sentry
38-
_hub.CaptureException(e);
30+
hub.CaptureException(e);
3931
}
4032
}, cancellationToken);
4133
}
4234

4335
public Task StopAsync(CancellationToken cancellationToken)
4436
{
45-
_logger.LogInformation("Stopping sample hosted service.");
37+
logger.LogInformation("Stopping sample hosted service.");
4638
return Task.CompletedTask;
4739
}
4840
}

samples/Sentry.Samples.GenericHost/Sentry.Samples.GenericHost.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net6.0</TargetFramework>
5+
<TargetFramework>net8.0</TargetFramework>
66
</PropertyGroup>
77

88
<ItemGroup>
@@ -13,7 +13,7 @@
1313

1414
<ItemGroup>
1515
<ProjectReference Include="..\..\src\Sentry.Extensions.Logging\Sentry.Extensions.Logging.csproj" />
16-
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
16+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
1717
</ItemGroup>
1818

1919
</Project>

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

Lines changed: 67 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,89 +1,81 @@
11
using Microsoft.Extensions.Logging;
22
using Sentry.Extensions.Logging;
33

4-
namespace Sentry.Samples.ME.Logging;
5-
6-
internal class Program
4+
using var loggerFactory = LoggerFactory.Create(builder =>
5+
{
6+
builder.AddConsole();
7+
builder.AddSentry(o =>
8+
{
9+
// Set to true to SDK debugging to see the internal messages through the logging library.
10+
o.Debug = false;
11+
// Configure the level of Sentry internal logging
12+
o.DiagnosticLevel = SentryLevel.Debug;
13+
14+
o.Dsn = "https://[email protected]/5428537";
15+
o.MaxBreadcrumbs = 150; // Increasing from default 100
16+
o.Release = "e386dfd"; // If not set here, SDK looks for it on main assembly's AssemblyInformationalVersion and AssemblyVersion
17+
18+
// Optionally configure options: The default values are:
19+
o.MinimumBreadcrumbLevel = LogLevel.Information; // It requires at least this level to store breadcrumb
20+
o.MinimumEventLevel = LogLevel.Error; // This level or above will result in event sent to Sentry
21+
22+
// Don't keep as a breadcrumb or send events for messages of level less than Critical with exception of type DivideByZeroException
23+
o.AddLogEntryFilter((_, level, _, exception) => level < LogLevel.Critical && exception is DivideByZeroException);
24+
25+
o.ConfigureScope(s => s.SetTag("RootScope", "sent with all events"));
26+
});
27+
});
28+
var logger = loggerFactory.CreateLogger<Program>();
29+
30+
logger.LogTrace("1 - By *default* this log level is ignored by Sentry.");
31+
32+
logger.LogInformation("2 - Information messages are stored as Breadcrumb, sent with the next event.");
33+
34+
// Won't add breadcrumb or record event due to the filter added above
35+
logger.LogError(new DivideByZeroException(), "Ignored because of the LogEntryFilter added via options.");
36+
37+
// Log messages with variables are grouped together.
38+
// This way a log message like: 'User {userId} logged in' doesn't generate 1 issue in Sentry for each user you have.
39+
// When visualizing this issue in Sentry, you can press Next and Back to see the individual log entries:
40+
logger.LogError("3 - This generates an event {id}, captured by sentry and includes breadcrumbs (2) tracked in this transaction.",
41+
100);
42+
logger.LogError("3 - This generates an event {id}, captured by sentry and includes breadcrumbs (2) tracked in this transaction.",
43+
999);
44+
45+
using (logger.BeginScope(new Dictionary<string, string>
46+
{
47+
{ "A", "some value" },
48+
{ "B", "more value" },
49+
}))
750
{
8-
private static void Main()
51+
logger.LogWarning("4 - Breadcrumb that only exists inside this scope");
52+
53+
logger.LogError("5 - An event that includes the scoped key-value (A, B) above and also the breadcrumbs: (2, 4) and event (3)");
54+
55+
using (logger.BeginScope("C - Inner most scope, with single string state"))
956
{
10-
using var loggerFactory = LoggerFactory.Create(builder =>
57+
logger.LogInformation("6 - Inner most breadcrumb");
58+
59+
try
1160
{
12-
builder.AddConsole();
13-
builder.AddSentry(o =>
14-
{
15-
// Set to true to SDK debugging to see the internal messages through the logging library.
16-
o.Debug = false;
17-
// Configure the level of Sentry internal logging
18-
o.DiagnosticLevel = SentryLevel.Debug;
19-
20-
o.Dsn = "https://[email protected]/5428537";
21-
o.MaxBreadcrumbs = 150; // Increasing from default 100
22-
o.Release = "e386dfd"; // If not set here, SDK looks for it on main assembly's AssemblyInformationalVersion and AssemblyVersion
23-
24-
// Optionally configure options: The default values are:
25-
o.MinimumBreadcrumbLevel = LogLevel.Information; // It requires at least this level to store breadcrumb
26-
o.MinimumEventLevel = LogLevel.Error; // This level or above will result in event sent to Sentry
27-
28-
// Don't keep as a breadcrumb or send events for messages of level less than Critical with exception of type DivideByZeroException
29-
o.AddLogEntryFilter((_, level, _, exception) => level < LogLevel.Critical && exception is DivideByZeroException);
30-
31-
o.ConfigureScope(s => s.SetTag("RootScope", "sent with all events"));
32-
});
33-
});
34-
var logger = loggerFactory.CreateLogger<Program>();
35-
36-
logger.LogTrace("1 - By *default* this log level is ignored by Sentry.");
37-
38-
logger.LogInformation("2 - Information messages are stored as Breadcrumb, sent with the next event.");
39-
40-
// Won't add breadcrumb or record event due to the filter added above
41-
logger.LogError(new DivideByZeroException(), "Ignored because of the LogEntryFilter added via options.");
42-
43-
// Log messages with variables are grouped together.
44-
// This way a log message like: 'User {userId} logged in' doesn't generate 1 issue in Sentry for each user you have.
45-
// When visualizing this issue in Sentry, you can press Next and Back to see the individual log entries:
46-
logger.LogError("3 - This generates an event {id}, captured by sentry and includes breadcrumbs (2) tracked in this transaction.",
47-
100);
48-
logger.LogError("3 - This generates an event {id}, captured by sentry and includes breadcrumbs (2) tracked in this transaction.",
49-
999);
50-
51-
using (logger.BeginScope(new Dictionary<string, string>
52-
{
53-
{"A", "some value"},
54-
{"B", "more value"},
55-
}))
61+
Dependency.Work("some work");
62+
}
63+
catch (Exception e)
5664
{
57-
logger.LogWarning("4 - Breadcrumb that only exists inside this scope");
58-
59-
logger.LogError("5 - An event that includes the scoped key-value (A, B) above and also the breadcrumbs: (2, 4) and event (3)");
60-
61-
using (logger.BeginScope("C - Inner most scope, with single string state"))
62-
{
63-
logger.LogInformation("6 - Inner most breadcrumb");
64-
65-
try
66-
{
67-
Dependency.Work("some work");
68-
}
69-
catch (Exception e)
70-
{
71-
// Handle an exception and log it:
72-
logger.LogError(e, "7 - An event that includes the scope key-value (A, B, C) and also the breadcrumbs: (2, 4, 6) and events (3, 5)");
73-
}
74-
} // Dispose scope C, drops state C and breadcrumb 6
75-
76-
// An exception that will go unhandled and crash the app:
77-
// Even though it's not caught nor logged, this error is captured by Sentry!
78-
// It will include all the scope data available up to this point
79-
Dependency.Work("8 - This unhandled exception is captured and includes Scope (A, B) and crumbs: (2, 4, 5) and event (3) ");
65+
// Handle an exception and log it:
66+
logger.LogError(e, "7 - An event that includes the scope key-value (A, B, C) and also the breadcrumbs: (2, 4, 6) and events (3, 5)");
8067
}
68+
} // Dispose scope C, drops state C and breadcrumb 6
8169

82-
// Disposing the LoggerFactory will close the SDK since it was initialized through
83-
// the integration while calling .Init()
84-
}
70+
// An exception that will go unhandled and crash the app:
71+
// Even though it's not caught nor logged, this error is captured by Sentry!
72+
// It will include all the scope data available up to this point
73+
Dependency.Work("8 - This unhandled exception is captured and includes Scope (A, B) and crumbs: (2, 4, 5) and event (3) ");
8574
}
8675

76+
// Disposing the LoggerFactory will close the SDK since it was initialized through
77+
// the integration while calling .Init()
78+
8779
internal static class Dependency
8880
{
8981
private static int Counter;

samples/Sentry.Samples.ME.Logging/Sentry.Samples.ME.Logging.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net6.0</TargetFramework>
5+
<TargetFramework>net8.0</TargetFramework>
66
</PropertyGroup>
77

88
<ItemGroup>

0 commit comments

Comments
 (0)