sentry-dotnet-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSentry .NET SDK
Sentry .NET SDK
Opinionated wizard that scans your .NET project and guides you through complete Sentry setup: error monitoring, distributed tracing, profiling, structured logging, and cron monitoring across all major .NET frameworks.
这个开箱即用的向导会扫描你的.NET项目,引导你完成完整的Sentry配置:覆盖所有主流.NET框架的错误监控、分布式链路追踪、性能剖析、结构化日志和定时任务监控。
Invoke This Skill When
适用场景
- User asks to "add Sentry to .NET", "set up Sentry in C#", or "install Sentry for ASP.NET Core"
- User wants error monitoring, tracing, profiling, logging, or crons for a .NET app
- User mentions ,
SentrySdk.Init,UseSentry, orSentry.AspNetCoreSentry.Maui - User wants to capture unhandled exceptions in WPF, WinForms, MAUI, or Azure Functions
- User asks about ,
SentryOptions,BeforeSend, or symbol uploadTracesSampleRate
Note: SDK version and APIs below reflectNuGet packages ≥6.1.0. Always verify against docs.sentry.io/platforms/dotnet/ before implementing.Sentry
- 用户要求「给.NET添加Sentry」、「在C#中配置Sentry」或「为ASP.NET Core安装Sentry」
- 用户需要为.NET应用配置错误监控、链路追踪、性能剖析、日志记录或定时任务监控
- 用户提到、
SentrySdk.Init、UseSentry或Sentry.AspNetCoreSentry.Maui - 用户需要在WPF、WinForms、MAUI或Azure Functions中捕获未处理异常
- 用户询问、
SentryOptions、BeforeSend或符号上传相关问题TracesSampleRate
注意: 下方的SDK版本和API对应≥6.1.0版本的NuGet包。 实施前请始终参考 docs.sentry.io/platforms/dotnet/ 确认最新规范。Sentry
Phase 1: Detect
阶段1:项目检测
Run these commands to understand the project before making any recommendations:
bash
undefined在给出任何推荐方案前,先运行以下命令了解项目信息:
bash
undefinedDetect framework type — find all .csproj files
检测框架类型 — 查找所有.csproj文件
find . -name "*.csproj" | head -20
find . -name "*.csproj" | head -20
Detect framework targets
检测框架目标版本
grep -r "TargetFramework|Project Sdk" --include="*.csproj" .
grep -r "TargetFramework|Project Sdk" --include="*.csproj" .
Check for existing Sentry packages
检查是否已安装Sentry包
grep -r "Sentry" --include="*.csproj" . | grep "PackageReference"
grep -r "Sentry" --include="*.csproj" . | grep "PackageReference"
Check startup files
检查启动文件
ls Program.cs src/Program.cs App.xaml.cs MauiProgram.cs 2>/dev/null
ls Program.cs src/Program.cs App.xaml.cs MauiProgram.cs 2>/dev/null
Check for appsettings
检查配置文件
ls appsettings.json src/appsettings.json 2>/dev/null
ls appsettings.json src/appsettings.json 2>/dev/null
Check for logging libraries
检查日志库
grep -r "Serilog|NLog|log4net" --include="*.csproj" .
grep -r "Serilog|NLog|log4net" --include="*.csproj" .
Check for companion frontend
检查是否存在配套前端项目
ls ../frontend ../client ../web 2>/dev/null
cat ../package.json 2>/dev/null | grep -E '"next"|"react"|"vue"' | head -3
**What to determine:**
| Question | Impact |
|----------|--------|
| Framework type? | Determines correct package and init pattern |
| .NET version? | .NET 8+ recommended; .NET Framework 4.6.2+ supported |
| Sentry already installed? | Skip install, go to feature config |
| Logging library (Serilog, NLog)? | Recommend matching Sentry sink/target |
| Async/hosted app (ASP.NET Core)? | `UseSentry()` on `WebHost`; no `IsGlobalModeEnabled` needed |
| Desktop app (WPF, WinForms, WinUI)? | Must set `IsGlobalModeEnabled = true` |
| Serverless (Azure Functions, Lambda)? | Must set `FlushOnCompletedRequest = true` |
| Frontend directory found? | Trigger Phase 4 cross-link |
**Framework → Package mapping:**
| Detected | Package to install |
|----------|--------------------|
| `Sdk="Microsoft.NET.Sdk.Web"` (ASP.NET Core) | `Sentry.AspNetCore` |
| `App.xaml.cs` with `Application` base | `Sentry` (WPF) |
| `[STAThread]` in `Program.cs` | `Sentry` (WinForms) |
| `MauiProgram.cs` | `Sentry.Maui` |
| `WebAssemblyHostBuilder` | `Sentry.AspNetCore.Blazor.WebAssembly` |
| `FunctionsStartup` | `Sentry.Extensions.Logging` + `Sentry.OpenTelemetry` |
| `HttpApplication` / `Global.asax` | `Sentry.AspNet` |
| Generic host / Worker Service | `Sentry.Extensions.Logging` |
---ls ../frontend ../client ../web 2>/dev/null
cat ../package.json 2>/dev/null | grep -E '"next"|"react"|"vue"' | head -3
**需要确认的信息:**
| 问题 | 影响 |
|----------|--------|
| 框架类型? | 决定要安装的正确包和初始化方式 |
| .NET版本? | 推荐使用.NET 8+;支持.NET Framework 4.6.2+ |
| 是否已安装Sentry? | 跳过安装步骤,直接进入功能配置 |
| 使用的日志库(Serilog、NLog)? | 推荐匹配对应的Sentry sink/target |
| 异步/托管应用(ASP.NET Core)? | 在`WebHost`上调用`UseSentry()`;无需设置`IsGlobalModeEnabled` |
| 桌面应用(WPF、WinForms、WinUI)? | 必须设置`IsGlobalModeEnabled = true` |
| 无服务应用(Azure Functions、Lambda)? | 必须设置`FlushOnCompletedRequest = true` |
| 找到前端项目目录? | 触发阶段4的跨端关联步骤 |
**框架 → 安装包映射:**
| 检测到的特征 | 需要安装的包 |
|----------|--------------------|
| `Sdk="Microsoft.NET.Sdk.Web"` (ASP.NET Core) | `Sentry.AspNetCore` |
| 继承自`Application`的`App.xaml.cs` | `Sentry` (WPF) |
| `Program.cs`中存在`[STAThread]` | `Sentry` (WinForms) |
| 存在`MauiProgram.cs` | `Sentry.Maui` |
| 存在`WebAssemblyHostBuilder` | `Sentry.AspNetCore.Blazor.WebAssembly` |
| 存在`FunctionsStartup` | `Sentry.Extensions.Logging` + `Sentry.OpenTelemetry` |
| 存在`HttpApplication` / `Global.asax` | `Sentry.AspNet` |
| 通用主机 / Worker Service | `Sentry.Extensions.Logging` |
---Phase 2: Recommend
阶段2:方案推荐
Present a concrete recommendation based on what you found. Lead with a proposal — don't ask open-ended questions.
Recommended (core coverage):
- ✅ Error Monitoring — always; captures unhandled exceptions, structured captures, scope enrichment
- ✅ Tracing — always for ASP.NET Core and hosted apps; auto-instruments HTTP requests and EF Core queries
- ✅ Logging — recommended for all apps; routes ILogger / Serilog / NLog entries to Sentry as breadcrumbs and events
Optional (enhanced observability):
- ⚡ Profiling — CPU profiling; recommend for performance-critical services running on .NET 6+
- ⚡ Crons — detect missed/failed scheduled jobs; recommend when Hangfire, Quartz.NET, or scheduled endpoints detected
Recommendation logic:
| Feature | Recommend when... |
|---|---|
| Error Monitoring | Always — non-negotiable baseline |
| Tracing | Always for ASP.NET Core — request traces, EF Core spans, HttpClient spans are high-value |
| Logging | App uses |
| Profiling | Performance-critical service on .NET 6+ |
| Crons | App uses Hangfire, Quartz.NET, or scheduled Azure Functions |
Propose: "I recommend setting up Error Monitoring + Tracing + Logging. Want me to also add Profiling or Crons?"
根据检测结果给出具体的推荐方案,直接给出提案,不要提开放式问题。
推荐基础配置(核心能力覆盖):
- ✅ 错误监控 — 必选;捕获未处理异常、结构化上报、上下文信息丰富
- ✅ 链路追踪 — ASP.NET Core和托管应用必选;自动埋点HTTP请求和EF Core查询
- ✅ 日志集成 — 所有应用推荐;将ILogger / Serilog / NLog日志作为面包屑和事件上报到Sentry
可选增强配置(提升可观测性):
- ⚡ 性能剖析 — CPU性能分析;推荐运行在.NET 6+的性能敏感服务使用
- ⚡ 定时任务监控 — 检测漏执行/失败的定时任务;当检测到Hangfire、Quartz.NET或定时端点时推荐使用
推荐逻辑:
| 功能 | 推荐场景 |
|---|---|
| 错误监控 | 始终推荐 — 基础必备能力 |
| 链路追踪 | ASP.NET Core应用始终推荐 — 请求链路、EF Core span、HttpClient span价值很高 |
| 日志集成 | 应用使用 |
| 性能剖析 | 运行在.NET 6+的性能敏感服务 |
| 定时任务监控 | 应用使用Hangfire、Quartz.NET或定时Azure Functions时 |
推荐话术:「我建议配置错误监控+链路追踪+日志集成,需要我额外添加性能剖析或定时任务监控吗?」
Phase 3: Guide
阶段3:配置指引
Option 1: Wizard (Recommended)
方案1:向导配置(推荐)
bash
npx @sentry/wizard@latest -i dotnetThe wizard logs you into Sentry, selects your org and project, configures your DSN, and sets up MSBuild symbol upload for readable stack traces in production.
Skip to Verification after running the wizard.
bash
npx @sentry/wizard@latest -i dotnet向导会引导你登录Sentry,选择组织和项目,配置DSN,同时设置MSBuild符号上传,方便生产环境下获得可读的堆栈跟踪。
运行完向导后直接跳转到验证环节。
Option 2: Manual Setup
方案2:手动配置
Install the right package
安装对应包
bash
undefinedbash
undefinedASP.NET Core
ASP.NET Core
dotnet add package Sentry.AspNetCore -v 6.1.0
dotnet add package Sentry.AspNetCore -v 6.1.0
WPF or WinForms or Console
WPF、WinForms或控制台应用
dotnet add package Sentry -v 6.1.0
dotnet add package Sentry -v 6.1.0
.NET MAUI
.NET MAUI
dotnet add package Sentry.Maui -v 6.1.0
dotnet add package Sentry.Maui -v 6.1.0
Blazor WebAssembly
Blazor WebAssembly
dotnet add package Sentry.AspNetCore.Blazor.WebAssembly -v 6.1.0
dotnet add package Sentry.AspNetCore.Blazor.WebAssembly -v 6.1.0
Azure Functions (Isolated Worker)
Azure Functions (隔离工作进程)
dotnet add package Sentry.Extensions.Logging -v 6.1.0
dotnet add package Sentry.OpenTelemetry -v 6.1.0
dotnet add package Sentry.Extensions.Logging -v 6.1.0
dotnet add package Sentry.OpenTelemetry -v 6.1.0
Classic ASP.NET (System.Web / .NET Framework)
传统ASP.NET (System.Web / .NET Framework)
dotnet add package Sentry.AspNet -v 6.1.0
---dotnet add package Sentry.AspNet -v 6.1.0
---ASP.NET Core — Program.cs
Program.csASP.NET Core — Program.cs
Program.cscsharp
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseSentry(options =>
{
options.Dsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "___YOUR_DSN___";
options.Debug = true; // disable in production
options.SendDefaultPii = true; // captures user IP, name, email
options.MaxRequestBodySize = RequestSize.Always;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Warning;
options.TracesSampleRate = 1.0; // tune to 0.1–0.2 in production
options.SetBeforeSend((@event, hint) =>
{
@event.ServerName = null; // scrub hostname from events
return @event;
});
});
var app = builder.Build();
app.Run();appsettings.jsonjson
{
"Sentry": {
"Dsn": "___YOUR_DSN___",
"SendDefaultPii": true,
"MaxRequestBodySize": "Always",
"MinimumBreadcrumbLevel": "Debug",
"MinimumEventLevel": "Warning",
"AttachStacktrace": true,
"Debug": true,
"TracesSampleRate": 1.0,
"Environment": "production",
"Release": "my-app@1.0.0"
}
}Environment variables (double underscore as separator):
bash
export Sentry__Dsn="https://examplePublicKey@o0.ingest.sentry.io/0"
export Sentry__TracesSampleRate="0.1"
export Sentry__Environment="staging"csharp
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseSentry(options =>
{
options.Dsn = Environment.GetEnvironmentVariable("SENTRY_DSN")
?? "___YOUR_DSN___";
options.Debug = true; // 生产环境请关闭
options.SendDefaultPii = true; // 捕获用户IP、姓名、邮箱
options.MaxRequestBodySize = RequestSize.Always;
options.MinimumBreadcrumbLevel = LogLevel.Debug;
options.MinimumEventLevel = LogLevel.Warning;
options.TracesSampleRate = 1.0; // 生产环境调整为0.1–0.2
options.SetBeforeSend((@event, hint) =>
{
@event.ServerName = null; // 移除事件中的主机名
return @event;
});
});
var app = builder.Build();
app.Run();appsettings.jsonjson
{
"Sentry": {
"Dsn": "___YOUR_DSN___",
"SendDefaultPii": true,
"MaxRequestBodySize": "Always",
"MinimumBreadcrumbLevel": "Debug",
"MinimumEventLevel": "Warning",
"AttachStacktrace": true,
"Debug": true,
"TracesSampleRate": 1.0,
"Environment": "production",
"Release": "my-app@1.0.0"
}
}环境变量配置(使用双下划线作为分隔符):
bash
export SENTRY__Dsn="https://examplePublicKey@o0.ingest.sentry.io/0"
export SENTRY__TracesSampleRate="0.1"
export SENTRY__Environment="staging"WPF — App.xaml.cs
App.xaml.csWPF — App.xaml.cs
App.xaml.cs⚠️ Critical: Initialize in the constructor, NOT in. The constructor fires earlier, catching more failure modes.OnStartup()
csharp
using System.Windows;
using Sentry;
public partial class App : Application
{
public App()
{
SentrySdk.Init(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.SendDefaultPii = true;
options.TracesSampleRate = 1.0;
options.IsGlobalModeEnabled = true; // required for all desktop apps
});
// Capture WPF UI-thread exceptions before WPF's crash dialog appears
DispatcherUnhandledException += App_DispatcherUnhandledException;
}
private void App_DispatcherUnhandledException(
object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
SentrySdk.CaptureException(e.Exception);
// Set e.Handled = true to prevent crash dialog and keep app running
}
}⚠️ 关键提示: 在构造函数中初始化,不要在中初始化。构造函数触发时机更早,能捕获更多异常场景。OnStartup()
csharp
using System.Windows;
using Sentry;
public partial class App : Application
{
public App()
{
SentrySdk.Init(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.SendDefaultPii = true;
options.TracesSampleRate = 1.0;
options.IsGlobalModeEnabled = true; // 所有桌面应用必须设置
});
// 在WPF崩溃弹窗出现前捕获UI线程异常
DispatcherUnhandledException += App_DispatcherUnhandledException;
}
private void App_DispatcherUnhandledException(
object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
SentrySdk.CaptureException(e.Exception);
// 设置e.Handled = true可阻止崩溃弹窗,保持应用继续运行
}
}WinForms — Program.cs
Program.csWinForms — Program.cs
Program.cscsharp
using System;
using System.Windows.Forms;
using Sentry;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Required: allows Sentry to see unhandled WinForms exceptions
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
using (SentrySdk.Init(new SentryOptions
{
Dsn = "___YOUR_DSN___",
Debug = true,
TracesSampleRate = 1.0,
IsGlobalModeEnabled = true, // required for desktop apps
}))
{
Application.Run(new MainForm());
} // Disposing flushes all pending events
}
}csharp
using System;
using System.Windows.Forms;
using Sentry;
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// 必需配置:让Sentry可以捕获未处理的WinForms异常
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
using (SentrySdk.Init(new SentryOptions
{
Dsn = "___YOUR_DSN___",
Debug = true,
TracesSampleRate = 1.0,
IsGlobalModeEnabled = true, // 桌面应用必需设置
}))
{
Application.Run(new MainForm());
} // Dispose时会刷新所有待上报的事件
}
}.NET MAUI — MauiProgram.cs
MauiProgram.cs.NET MAUI — MauiProgram.cs
MauiProgram.cscsharp
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.SendDefaultPii = true;
options.TracesSampleRate = 1.0;
// MAUI-specific: opt-in breadcrumbs (off by default — PII risk)
options.IncludeTextInBreadcrumbs = false;
options.IncludeTitleInBreadcrumbs = false;
options.IncludeBackgroundingStateInBreadcrumbs = false;
});
return builder.Build();
}
}csharp
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder
.UseMauiApp<App>()
.UseSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.SendDefaultPii = true;
options.TracesSampleRate = 1.0;
// MAUI专属配置:可选面包屑(默认关闭 — 存在PII泄露风险)
options.IncludeTextInBreadcrumbs = false;
options.IncludeTitleInBreadcrumbs = false;
options.IncludeBackgroundingStateInBreadcrumbs = false;
});
return builder.Build();
}
}Blazor WebAssembly — Program.cs
Program.csBlazor WebAssembly — Program.cs
Program.cscsharp
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.UseSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.SendDefaultPii = true;
options.TracesSampleRate = 0.1;
});
// Hook logging pipeline without re-initializing the SDK
builder.Logging.AddSentry(o => o.InitializeSdk = false);
await builder.Build().RunAsync();csharp
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.UseSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.SendDefaultPii = true;
options.TracesSampleRate = 0.1;
});
// 无需重新初始化SDK即可接入日志流水线
builder.Logging.AddSentry(o => o.InitializeSdk = false);
await builder.Build().RunAsync();Azure Functions (Isolated Worker) — Program.cs
Program.csAzure Functions (隔离工作进程) — Program.cs
Program.cscsharp
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Trace;
using Sentry.OpenTelemetry;
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
services.AddOpenTelemetry().WithTracing(builder =>
{
builder
.AddSentry() // route OTel spans to Sentry
.AddHttpClientInstrumentation(); // capture outgoing HTTP
});
})
.ConfigureLogging(logging =>
{
logging.AddSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.TracesSampleRate = 1.0;
options.UseOpenTelemetry(); // let OTel drive tracing
options.DisableSentryHttpMessageHandler = true; // prevent duplicate HTTP spans
});
})
.Build();
await host.RunAsync();csharp
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Trace;
using Sentry.OpenTelemetry;
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
services.AddOpenTelemetry().WithTracing(builder =>
{
builder
.AddSentry() // 将OTel span转发到Sentry
.AddHttpClientInstrumentation(); // 捕获出站HTTP请求
});
})
.ConfigureLogging(logging =>
{
logging.AddSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.Debug = true;
options.TracesSampleRate = 1.0;
options.UseOpenTelemetry(); // 让OTel负责链路追踪
options.DisableSentryHttpMessageHandler = true; // 避免重复上报HTTP span
});
})
.Build();
await host.RunAsync();AWS Lambda — LambdaEntryPoint.cs
LambdaEntryPoint.csAWS Lambda — LambdaEntryPoint.cs
LambdaEntryPoint.cscsharp
public class LambdaEntryPoint : APIGatewayProxyFunction
{
protected override void Init(IWebHostBuilder builder)
{
builder
.UseSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.TracesSampleRate = 1.0;
options.FlushOnCompletedRequest = true; // REQUIRED for Lambda
})
.UseStartup<Startup>();
}
}csharp
public class LambdaEntryPoint : APIGatewayProxyFunction
{
protected override void Init(IWebHostBuilder builder)
{
builder
.UseSentry(options =>
{
options.Dsn = "___YOUR_DSN___";
options.TracesSampleRate = 1.0;
options.FlushOnCompletedRequest = true; // Lambda环境必需配置
})
.UseStartup<Startup>();
}
}Classic ASP.NET — Global.asax.cs
Global.asax.cs传统ASP.NET — Global.asax.cs
Global.asax.cscsharp
public class MvcApplication : HttpApplication
{
private IDisposable _sentry;
protected void Application_Start()
{
_sentry = SentrySdk.Init(options =>
{
options.Dsn = "___YOUR_DSN___";
options.TracesSampleRate = 1.0;
options.AddEntityFramework(); // EF6 query breadcrumbs
options.AddAspNet(); // Classic ASP.NET integration
});
}
protected void Application_Error() => Server.CaptureLastError();
protected void Application_BeginRequest() => Context.StartSentryTransaction();
protected void Application_EndRequest() => Context.FinishSentryTransaction();
protected void Application_End() => _sentry?.Dispose();
}csharp
public class MvcApplication : HttpApplication
{
private IDisposable _sentry;
protected void Application_Start()
{
_sentry = SentrySdk.Init(options =>
{
options.Dsn = "___YOUR_DSN___";
options.TracesSampleRate = 1.0;
options.AddEntityFramework(); // EF6查询面包屑
options.AddAspNet(); // 传统ASP.NET集成
});
}
protected void Application_Error() => Server.CaptureLastError();
protected void Application_BeginRequest() => Context.StartSentryTransaction();
protected void Application_EndRequest() => Context.FinishSentryTransaction();
protected void Application_End() => _sentry?.Dispose();
}Symbol Upload (Readable Stack Traces)
符号上传(获取可读堆栈跟踪)
Without debug symbols, stack traces show only method names — no file names or line numbers. Upload PDB files to unlock full source context.
Step 1: Create a Sentry auth token
Step 2: Add MSBuild properties to or :
.csprojDirectory.Build.propsxml
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<SentryOrg>___ORG_SLUG___</SentryOrg>
<SentryProject>___PROJECT_SLUG___</SentryProject>
<SentryUploadSymbols>true</SentryUploadSymbols>
<SentryUploadSources>true</SentryUploadSources>
<SentryCreateRelease>true</SentryCreateRelease>
<SentrySetCommits>true</SentrySetCommits>
</PropertyGroup>Step 3: Set in CI:
SENTRY_AUTH_TOKENyaml
undefined如果没有调试符号,堆栈跟踪只会显示方法名,没有文件名和行号。上传PDB文件可以解锁完整的源码上下文。
步骤1:创建Sentry授权令牌
步骤2:在或中添加MSBuild属性:
.csprojDirectory.Build.propsxml
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<SentryOrg>___ORG_SLUG___</SentryOrg>
<SentryProject>___PROJECT_SLUG___</SentryProject>
<SentryUploadSymbols>true</SentryUploadSymbols>
<SentryUploadSources>true</SentryUploadSources>
<SentryCreateRelease>true</SentryCreateRelease>
<SentrySetCommits>true</SentrySetCommits>
</PropertyGroup>步骤3:在CI中设置:
SENTRY_AUTH_TOKENyaml
undefinedGitHub Actions
GitHub Actions示例
- name: Build & upload symbols run: dotnet build -c Release env: SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
---- name: Build & upload symbols run: dotnet build -c Release env: SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
---For Each Agreed Feature
针对每个同意启用的功能
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always — |
| Tracing | | Server apps, distributed tracing, EF Core spans, custom instrumentation |
| Profiling | | Performance-critical apps on .NET 6+ |
| Logging | | |
| Crons | | Hangfire, Quartz.NET, or scheduled function monitoring |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
加载对应的参考文件并严格按照步骤操作:
| 功能 | 参考文件 | 触发场景 |
|---|---|---|
| 错误监控 | | 始终加载 — 包含 |
| 链路追踪 | | 服务端应用、分布式追踪、EF Core span、自定义埋点场景 |
| 性能剖析 | | 运行在.NET 6+的性能敏感应用 |
| 日志集成 | | |
| 定时任务监控 | | Hangfire、Quartz.NET或定时函数监控场景 |
针对每个功能:阅读参考文件,严格按照步骤操作,验证通过后再进行下一步。
Verification
验证环节
After wizard or manual setup, add a test throw and remove it after verifying:
csharp
// ASP.NET Core: add a temporary endpoint
app.MapGet("/sentry-test", () =>
{
throw new Exception("Sentry test error — delete me");
});
// Or capture explicitly anywhere
SentrySdk.CaptureException(new Exception("Sentry test error — delete me"));Then check your Sentry Issues dashboard — the error should appear within ~30 seconds.
Verification checklist:
| Check | How |
|---|---|
| Exceptions captured | Throw a test exception, verify in Sentry Issues |
| Stack traces readable | Check that file names and line numbers appear |
| Tracing active | Check Performance tab for transactions |
| Logging wired | Log an error via |
| Symbol upload working | Stack trace shows |
通过向导或手动配置完成后,添加一个测试异常,验证通过后再删除:
csharp
// ASP.NET Core:添加一个临时端点
app.MapGet("/sentry-test", () =>
{
throw new Exception("Sentry测试异常 — 请删除我");
});
// 或在任意位置主动上报
SentrySdk.CaptureException(new Exception("Sentry测试异常 — 请删除我"));然后检查你的Sentry问题面板 — 异常应该会在30秒内出现。
验证清单:
| 检查项 | 验证方式 |
|---|---|
| 异常已捕获 | 抛出测试异常,在Sentry问题面板中确认存在 |
| 堆栈跟踪可读 | 检查是否显示文件名和行号 |
| 链路追踪已启用 | 检查性能面板是否存在事务 |
| 日志已接入 | 通过 |
| 符号上传正常 | 堆栈跟踪显示 |
Config Reference
配置参考
Core SentryOptions
SentryOptions核心SentryOptions
SentryOptions| Option | Type | Default | Env Var | Notes |
|---|---|---|---|---|
| | — | | Required. SDK disabled if unset. |
| | | — | SDK diagnostic output. Disable in production. |
| | | — | |
| | auto | | Auto-detected from assembly version + git SHA |
| | | | |
| | — | — | Build variant. Max 64 chars. |
| | | — | Error event sampling rate 0.0–1.0 |
| | | — | Transaction sampling. Must be |
| | — | — | Per-transaction dynamic sampler; overrides |
| | | — | Fraction of traced transactions to profile. Requires |
| | | — | Include user IP, name, email |
| | | — | Attach stack trace to all messages |
| | | — | Max breadcrumbs stored per event |
| | | — | *Auto- |
| | | — | *Auto- |
| | | — | Auto-capture HTTP client errors |
| | — | — | Offline event caching directory |
| | — | — | Max wait for event flush on shutdown |
| | — | — | Proxy URL for Sentry requests |
| | | — | Auto-reduce sample rates on delivery failures |
| 配置项 | 类型 | 默认值 | 环境变量 | 说明 |
|---|---|---|---|---|
| | — | | 必需。未设置时SDK会禁用。 |
| | | — | SDK诊断日志输出,生产环境请关闭。 |
| | | — | 可选值: |
| | 自动获取 | | 从程序集版本+git SHA自动检测 |
| | | | 调试器挂载时为 |
| | — | — | 构建变体,最多64个字符。 |
| | | — | 错误事件采样率,范围0.0–1.0 |
| | | — | 事务采样率,必须 |
| | — | — | 按事务动态设置采样率,优先级高于 |
| | | — | 需进行性能剖析的事务占比,需要安装 |
| | | — | 包含用户IP、姓名、邮箱 |
| | | — | 为所有消息附加堆栈跟踪 |
| | | — | 每个事件最多存储的面包屑数量 |
| | | — | *MAUI、Blazor WASM自动设为 |
| | | — | *MAUI自动设为 |
| | | — | 自动捕获HTTP客户端错误 |
| | — | — | 离线事件缓存目录 |
| | — | — | 关闭时等待事件上报的最长时间 |
| | — | — | Sentry请求的代理URL |
| | | — | 上报失败时自动降低采样率 |
ASP.NET Core Extended Options (SentryAspNetCoreOptions
)
SentryAspNetCoreOptionsASP.NET Core扩展配置(SentryAspNetCoreOptions
)
SentryAspNetCoreOptions| Option | Type | Default | Notes |
|---|---|---|---|
| | | |
| | | Min log level for breadcrumbs |
| | | Min log level to send as Sentry event |
| | | Detect |
| | | Required for Lambda / serverless |
| | | Capture |
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | | 可选值: |
| | | 面包屑的最低日志级别 |
| | | 作为Sentry事件上报的最低日志级别 |
| | | 检测 |
| | | Lambda/无服务环境必需配置 |
| | | 捕获 |
MAUI Extended Options (SentryMauiOptions
)
SentryMauiOptionsMAUI扩展配置(SentryMauiOptions
)
SentryMauiOptions| Option | Type | Default | Notes |
|---|---|---|---|
| | | Text from |
| | | Titles from |
| | | |
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| | | 来自 |
| | | 来自 |
| | | |
Environment Variables
环境变量
| Variable | Purpose |
|---|---|
| Project DSN |
| App version (e.g. |
| Deployment environment name |
| MSBuild / |
ASP.NET Core: use double underscore as hierarchy separator:
__bash
export Sentry__Dsn="https://..."
export Sentry__TracesSampleRate="0.1"| 变量 | 用途 |
|---|---|
| 项目DSN |
| 应用版本(例如 |
| 部署环境名称 |
| MSBuild / |
ASP.NET Core: 使用双下划线作为层级分隔符:
__bash
export SENTRY__Dsn="https://..."
export SENTRY__TracesSampleRate="0.1"MSBuild Symbol Upload Properties
MSBuild符号上传属性
| Property | Type | Default | Description |
|---|---|---|---|
| | — | Sentry organization slug |
| | — | Sentry project slug |
| | | Upload PDB files for line numbers in stack traces |
| | | Upload source files for source context |
| | | Auto-create a Sentry release during build |
| | | Associate git commits with the release |
| | — | Self-hosted Sentry URL |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| | — | Sentry组织标识 |
| | — | Sentry项目标识 |
| | | 上传PDB文件,用于显示堆栈跟踪的行号 |
| | | 上传源文件,用于展示源码上下文 |
| | | 构建时自动创建Sentry版本 |
| | | 将git提交与版本关联 |
| | — | 自托管Sentry的URL |
Phase 4: Cross-Link
阶段4:跨端关联
After completing .NET setup, check for companion frontend projects:
bash
undefined完成.NET配置后,检查是否存在配套的前端项目:
bash
undefinedCheck for frontend in adjacent directories
检查相邻目录中的前端项目
ls ../frontend ../client ../web ../app 2>/dev/null
ls ../frontend ../client ../web ../app 2>/dev/null
Check for JavaScript framework indicators
检查JavaScript框架标识
cat ../package.json 2>/dev/null | grep -E '"next"|"react"|"vue"|"nuxt"' | head -3
If a frontend is found, suggest the matching SDK skill:
| Frontend detected | Suggest skill |
|-------------------|--------------|
| Next.js (`"next"` in `package.json`) | `sentry-nextjs-sdk` |
| React SPA (`"react"` without `"next"`) | `@sentry/react` — see [docs.sentry.io/platforms/javascript/guides/react/](https://docs.sentry.io/platforms/javascript/guides/react/) |
| Vue.js | `@sentry/vue` — see [docs.sentry.io/platforms/javascript/guides/vue/](https://docs.sentry.io/platforms/javascript/guides/vue/) |
| Nuxt | `@sentry/nuxt` — see [docs.sentry.io/platforms/javascript/guides/nuxt/](https://docs.sentry.io/platforms/javascript/guides/nuxt/) |
Connecting frontend and backend with the same Sentry project enables **distributed tracing** — a single trace view spanning browser, .NET server, and any downstream APIs.
---cat ../package.json 2>/dev/null | grep -E '"next"|"react"|"vue"|"nuxt"' | head -3
如果检测到前端项目,推荐对应的SDK技能:
| 检测到的前端 | 推荐技能 |
|-------------------|--------------|
| Next.js(`package.json`中存在`"next"`) | `sentry-nextjs-sdk` |
| React SPA(存在`"react"`但无`"next"`) | `@sentry/react` — 参考 [docs.sentry.io/platforms/javascript/guides/react/](https://docs.sentry.io/platforms/javascript/guides/react/) |
| Vue.js | `@sentry/vue` — 参考 [docs.sentry.io/platforms/javascript/guides/vue/](https://docs.sentry.io/platforms/javascript/guides/vue/) |
| Nuxt | `@sentry/nuxt` — 参考 [docs.sentry.io/platforms/javascript/guides/nuxt/](https://docs.sentry.io/platforms/javascript/guides/nuxt/) |
将前端和后端接入同一个Sentry项目可以实现**分布式链路追踪** — 单个链路视图可以覆盖浏览器、.NET服务端和所有下游API。
---Troubleshooting
问题排查
| Issue | Cause | Solution |
|---|---|---|
| Events not appearing | DSN misconfigured | Set |
| Stack traces show no file/line | PDB files not uploaded | Add |
| WPF/WinForms exceptions missing | | Set |
| Lambda/serverless events lost | Container freezes before flush | Set |
| WPF UI-thread exceptions missing | | Register |
| Duplicate HTTP spans in Azure Functions | Both Sentry and OTel instrument HTTP | Set |
| Rate is | Set |
| Config key format wrong | Use flat key |
| Hook returns | Verify your filter logic; return |
| MAUI native crashes not captured | Wrong package | Confirm |
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未出现 | DSN配置错误 | 设置 |
| 堆栈跟踪没有显示文件/行号 | 未上传PDB文件 | 在 |
| WPF/WinForms异常缺失 | 未设置 | 在 |
| Lambda/无服务事件丢失 | 容器在上报完成前冻结 | 设置 |
| WPF UI线程异常缺失 | 未绑定 | 在构造函数中注册 |
| Azure Functions中出现重复HTTP span | Sentry和OTel都对HTTP做了埋点 | 设置 |
| 采样率为默认值 | 设置 |
| 配置键格式错误 | 使用扁平化键 |
| 钩子无条件返回 | 检查过滤逻辑;仅对需要丢弃的事件返回 |
| MAUI原生崩溃未捕获 | 安装的包不正确 | 确认安装的是 |