sentry-dotnet-sdk by getsentry/sentry-for-ai
npx skills add https://github.com/getsentry/sentry-for-ai --skill sentry-dotnet-sdk一个经过精心设计的向导,用于扫描您的 .NET 项目并指导您完成完整的 Sentry 设置:涵盖所有主流 .NET 框架的错误监控、分布式追踪、性能剖析、结构化日志记录和定时任务监控。
SentrySdk.Init、UseSentry、Sentry.AspNetCore 或 Sentry.MauiSentryOptions、BeforeSend、 或符号文件上传的问题广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
TracesSampleRate注意: 下面的 SDK 版本和 API 反映了
SentryNuGet 包 ≥6.1.0 版本。在实施前,请务必对照 docs.sentry.io/platforms/dotnet/ 进行验证。
在提出任何建议之前,运行以下命令来了解项目:
# 检测框架类型 — 查找所有 .csproj 文件
find . -name "*.csproj" | head -20
# 检测框架目标
grep -r "TargetFramework\|Project Sdk" --include="*.csproj" .
# 检查是否已存在 Sentry 包
grep -r "Sentry" --include="*.csproj" . | grep "PackageReference"
# 检查启动文件
ls Program.cs src/Program.cs App.xaml.cs MauiProgram.cs 2>/dev/null
# 检查 appsettings 文件
ls appsettings.json src/appsettings.json 2>/dev/null
# 检查日志库
grep -r "Serilog\|NLog\|log4net" --include="*.csproj" .
# 检查配套的前端项目
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 接收器/目标 |
| 异步/托管应用(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 |
App.xaml.cs 且基类为 Application | 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 |
| 通用主机 / 工作服务 | Sentry.Extensions.Logging |
根据您的发现提出具体建议。以提案为主导 — 不要提出开放式问题。
推荐(核心覆盖范围):
可选(增强可观测性):
推荐逻辑:
| 功能 | 何时推荐... |
|---|---|
| 错误监控 | 始终 — 不可或缺的基线 |
| 追踪 | 对于 ASP.NET Core 始终启用 — 请求追踪、EF Core 跨度、HttpClient 跨度具有高价值 |
| 日志记录 | 应用使用 ILogger<T>、Serilog、NLog 或 log4net |
| 性能剖析 | 运行在 .NET 6+ 上的性能关键服务 |
| 定时任务监控 | 应用使用 Hangfire、Quartz.NET 或定时 Azure Functions |
提案:"我建议设置错误监控 + 追踪 + 日志记录。您还想让我添加性能剖析或定时任务监控吗?"
您需要自己运行此命令 — 向导会打开浏览器进行登录,并需要代理无法处理的交互式输入。请复制粘贴到您的终端:
npx @sentry/wizard@latest -i dotnet它会处理登录、组织/项目选择、DSN 配置以及用于生产环境中可读堆栈跟踪的 MSBuild 符号文件上传设置。
一旦完成,请返回并跳转到验证部分。
如果用户跳过向导,请继续下面的选项 2(手动设置)。
# ASP.NET Core
dotnet add package Sentry.AspNetCore -v 6.1.0
# WPF 或 WinForms 或 Console
dotnet add package Sentry -v 6.1.0
# .NET MAUI
dotnet add package Sentry.Maui -v 6.1.0
# Blazor WebAssembly
dotnet add package Sentry.AspNetCore.Blazor.WebAssembly -v 6.1.0
# Azure Functions (Isolated Worker)
dotnet add package Sentry.Extensions.Logging -v 6.1.0
dotnet add package Sentry.OpenTelemetry -v 6.1.0
# 经典 ASP.NET (System.Web / .NET Framework)
dotnet add package Sentry.AspNet -v 6.1.0
Program.csvar 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.json(替代配置):
{
"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"
}
}
环境变量(使用双下划线 __ 作为层级分隔符):
export Sentry__Dsn="https://examplePublicKey@o0.ingest.sentry.io/0"
export Sentry__TracesSampleRate="0.1"
export Sentry__Environment="staging"
App.xaml.cs⚠️ 关键: 在构造函数中初始化,而不是在
OnStartup()中。构造函数触发更早,能捕获更多故障模式。
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 的崩溃对话框出现之前捕获 WPF UI 线程异常
DispatcherUnhandledException += App_DispatcherUnhandledException;
}
private void App_DispatcherUnhandledException(
object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
SentrySdk.CaptureException(e.Exception);
// 设置 e.Handled = true 以防止崩溃对话框并保持应用运行
}
}
Program.csusing 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());
} // 释放时会刷新所有待处理的事件
}
}
MauiProgram.cspublic 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();
}
}
Program.csvar 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();
Program.csusing 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 跨度路由到 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 跨度
});
})
.Build();
await host.RunAsync();
LambdaEntryPoint.cspublic 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>();
}
}
Global.asax.cspublic 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();
}
没有调试符号,堆栈跟踪只显示方法名 — 没有文件名或行号。上传 PDB 文件以解锁完整的源代码上下文。
步骤 1:创建 Sentry 认证令牌
访问 sentry.io/settings/auth-tokens/ 并创建一个具有 project:releases 和 org:read 范围的令牌。
步骤 2:将 MSBuild 属性添加到.csproj 或 Directory.Build.props:
<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_TOKEN:
# GitHub Actions
- name: Build & upload symbols
run: dotnet build -c Release
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
加载相应的参考文件并遵循其步骤:
| 功能 | 参考文件 | 何时加载 |
|---|---|---|
| 错误监控 | references/error-monitoring.md | 始终 — CaptureException、作用域、增强、过滤 |
| 追踪 | references/tracing.md | 服务器应用、分布式追踪、EF Core 跨度、自定义检测 |
| 性能剖析 | references/profiling.md | 运行在 .NET 6+ 上的性能关键应用 |
| 日志记录 | references/logging.md | ILogger<T>、Serilog、NLog、log4net 集成 |
| 定时任务监控 | references/crons.md | Hangfire、Quartz.NET 或定时函数监控 |
对于每个功能:阅读参考文件,严格按照其步骤操作,并在继续之前进行验证。
在向导或手动设置之后,添加一个测试异常,并在验证后删除它:
// ASP.NET Core:添加一个临时端点
app.MapGet("/sentry-test", () =>
{
throw new Exception("Sentry 测试错误 — 请删除我");
});
// 或者在任何地方显式捕获
SentrySdk.CaptureException(new Exception("Sentry 测试错误 — 请删除我"));
然后检查您的 Sentry Issues 仪表板 — 错误应该在大约 30 秒内出现。
验证清单:
| 检查项 | 方法 |
|---|---|
| 异常已捕获 | 抛出一个测试异常,在 Sentry Issues 中验证 |
| 堆栈跟踪可读 | 检查是否出现文件名和行号 |
| 追踪已激活 | 检查 Performance 选项卡中的事务 |
| 日志记录已连接 | 通过 ILogger 记录一个错误,检查它是否作为 Sentry 面包屑出现 |
| 符号文件上传正常 | 堆栈跟踪显示 Controllers/HomeController.cs:42 而不是 <unknown> |
SentryOptions| 选项 | 类型 | 默认值 | 环境变量 | 说明 |
|---|---|---|---|---|
Dsn | string | — | SENTRY_DSN | 必需。如果未设置,SDK 将被禁用。 |
Debug | bool | false | — | SDK 诊断输出。在生产环境中禁用。 |
DiagnosticLevel | SentryLevel | Debug | — | Debug、Info、Warning、Error、Fatal |
Release | string | 自动 | SENTRY_RELEASE | 从程序集版本 + git SHA 自动检测 |
Environment | string | "production" | SENTRY_ENVIRONMENT | 当调试器附加时为 "debug" |
Dist | string | — | — | 构建变体。最多 64 个字符。 |
SampleRate | float | 1.0 | — | 错误事件采样率 0.0–1.0 |
TracesSampleRate | double | 0.0 | — | 事务采样。必须 > 0 才能启用。 |
TracesSampler | Func<SamplingContext, double> | — | — | 每个事务的动态采样器;覆盖 TracesSampleRate |
ProfilesSampleRate | double | 0.0 | — | 要进行性能剖析的已追踪事务的比例。需要 Sentry.Profiling。 |
SendDefaultPii | bool | false | — | 包含用户 IP、姓名、邮箱 |
AttachStacktrace | bool | true | — | 为所有消息附加堆栈跟踪 |
MaxBreadcrumbs | int | 100 | — | 每个事件存储的最大面包屑数量 |
IsGlobalModeEnabled | bool | false* | — | *对于 MAUI、Blazor WASM 自动设为 true。必须为 WPF、WinForms、Console 设为 true。 |
AutoSessionTracking | bool | false* | — | *对于 MAUI 自动设为 true。为 Release Health 启用。 |
CaptureFailedRequests | bool | true | — | 自动捕获 HTTP 客户端错误 |
CacheDirectoryPath | string | — | — | 离线事件缓存目录 |
ShutdownTimeout | TimeSpan | — | — | 关闭时等待事件刷新的最长时间 |
HttpProxy | string | — | — | Sentry 请求的代理 URL |
EnableBackpressureHandling | bool | true | — | 在交付失败时自动降低采样率 |
SentryAspNetCoreOptions)| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
MaxRequestBodySize | RequestSize | None | None、Small (~4 KB)、Medium (~10 KB)、Always |
MinimumBreadcrumbLevel | LogLevel | Information | 面包屑的最小日志级别 |
MinimumEventLevel | LogLevel | Error | 作为 Sentry 事件发送的最小日志级别 |
CaptureBlockingCalls | bool | false | 检测 .Wait() / .Result 线程池饥饿 |
FlushOnCompletedRequest | bool | false | Lambda / 无服务器应用必需 |
IncludeActivityData | bool | false | 捕获 System.Diagnostics.Activity 值 |
SentryMauiOptions)| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
IncludeTextInBreadcrumbs | bool | false | 来自 Button、Label、Entry 元素的文本。⚠️ PII 风险。 |
IncludeTitleInBreadcrumbs | bool | false | 来自 Window、Page 元素的标题。⚠️ PII 风险。 |
IncludeBackgroundingStateInBreadcrumbs | bool | false | Window.Backgrounding 事件状态。⚠️ PII 风险。 |
| 变量 | 用途 |
|---|---|
SENTRY_DSN | 项目 DSN |
SENTRY_RELEASE | 应用版本(例如 my-app@1.2.3) |
SENTRY_ENVIRONMENT | 部署环境名称 |
SENTRY_AUTH_TOKEN | MSBuild / sentry-cli 符号文件上传认证令牌 |
ASP.NET Core: 使用双下划线 __ 作为层级分隔符:
export Sentry__Dsn="https://..."
export Sentry__TracesSampleRate="0.1"
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
SentryOrg | string | — | Sentry 组织 slug |
SentryProject | string | — | Sentry 项目 slug |
SentryUploadSymbols | bool | false | 上传 PDB 文件以在堆栈跟踪中显示行号 |
SentryUploadSources | bool | false | 上传源文件以提供源代码上下文 |
SentryCreateRelease | bool | false | 在构建期间自动创建 Sentry 版本 |
SentrySetCommits | bool | false | 将 git 提交与版本关联 |
SentryUrl | string | — | 自托管的 Sentry URL |
完成 .NET 设置后,检查配套的前端项目:
# 检查相邻目录中的前端项目
ls ../frontend ../client ../web ../app 2>/dev/null
# 检查 JavaScript 框架指示器
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 (package.json 中有 "react" 但没有 "next") | @sentry/react — 参见 docs.sentry.io/platforms/javascript/guides/react/ |
| Vue.js | @sentry/vue — 参见 docs.sentry.io/platforms/javascript/guides/vue/ |
| Nuxt | @sentry/nuxt — 参见 docs.sentry.io/platforms/javascript/guides/nuxt/ |
将前端和后端连接到同一个 Sentry 项目可以实现分布式追踪 — 一个单一的追踪视图跨越浏览器、.NET 服务器和任何下游 API。
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 事件未出现 | DSN 配置错误 | 设置 Debug = true 并检查控制台输出中的 SDK 诊断消息 |
| 堆栈跟踪不显示文件/行号 | PDB 文件未上传 | 将 SentryUploadSymbols=true 添加到 .csproj;在 CI 中设置 SENTRY_AUTH_TOKEN |
| WPF/WinForms 异常缺失 | 未设置 IsGlobalModeEnabled | 在 SentrySdk.Init() 中设置 options.IsGlobalModeEnabled = true |
| Lambda/无服务器事件丢失 | 容器在刷新前冻结 | 设置 options.FlushOnCompletedRequest = true |
| WPF UI 线程异常缺失 | 未连接 DispatcherUnhandledException | 在构造函数中注册 App.DispatcherUnhandledException(而不是 OnStartup) |
| Azure Functions 中重复的 HTTP 跨度 | Sentry 和 OTel 都检测 HTTP | 设置 options.DisableSentryHttpMessageHandler = true |
TracesSampleRate 无效 | 采样率为 0.0(默认值) | 设置 TracesSampleRate > 0 以启用追踪 |
appsettings.json 值被忽略 | 配置键格式错误 | 使用扁平键 "Sentry:Dsn" 或环境变量 Sentry__Dsn(双下划线) |
BeforeSend 丢弃所有事件 | 钩子无条件返回 null | 验证您的过滤逻辑;仅对要丢弃的事件返回 null |
| MAUI 原生崩溃未捕获 | 包错误 | 确认已安装 Sentry.Maui(不仅仅是 Sentry) |
每周安装次数
167
仓库
GitHub 星标数
82
首次出现
2026年3月1日
安全审计
已安装于
codex166
gemini-cli163
cursor163
kimi-cli162
github-copilot162
amp162
All Skills > SDK Setup > .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.
SentrySdk.Init, UseSentry, Sentry.AspNetCore, or Sentry.MauiSentryOptions, BeforeSend, TracesSampleRate, or symbol uploadNote: SDK version and APIs below reflect
SentryNuGet packages ≥6.1.0. Always verify against docs.sentry.io/platforms/dotnet/ before implementing.
Run these commands to understand the project before making any recommendations:
# Detect framework type — find all .csproj files
find . -name "*.csproj" | head -20
# Detect framework targets
grep -r "TargetFramework\|Project Sdk" --include="*.csproj" .
# Check for existing Sentry packages
grep -r "Sentry" --include="*.csproj" . | grep "PackageReference"
# Check startup files
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
# Check for logging libraries
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 |
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) |
Present a concrete recommendation based on what you found. Lead with a proposal — don't ask open-ended questions.
Recommended (core coverage):
Optional (enhanced observability):
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 ILogger<T>, Serilog, NLog, or log4net |
| 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?"
You need to run this yourself — the wizard opens a browser for login and requires interactive input that the agent can't handle. Copy-paste into your terminal:
npx @sentry/wizard@latest -i dotnetIt handles login, org/project selection, DSN configuration, and MSBuild symbol upload setup for readable stack traces in production.
Once it finishes, come back and skip toVerification.
If the user skips the wizard, proceed with Option 2 (Manual Setup) below.
# ASP.NET Core
dotnet add package Sentry.AspNetCore -v 6.1.0
# WPF or WinForms or Console
dotnet add package Sentry -v 6.1.0
# .NET MAUI
dotnet add package Sentry.Maui -v 6.1.0
# Blazor WebAssembly
dotnet add package Sentry.AspNetCore.Blazor.WebAssembly -v 6.1.0
# Azure Functions (Isolated Worker)
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)
dotnet add package Sentry.AspNet -v 6.1.0
Program.csvar 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.json (alternative configuration):
{
"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):
export Sentry__Dsn="https://examplePublicKey@o0.ingest.sentry.io/0"
export Sentry__TracesSampleRate="0.1"
export Sentry__Environment="staging"
App.xaml.cs⚠️ Critical: Initialize in the constructor , NOT in
OnStartup(). The constructor fires earlier, catching more failure modes.
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
}
}
Program.csusing 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
}
}
MauiProgram.cspublic 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();
}
}
Program.csvar 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();
Program.csusing 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();
LambdaEntryPoint.cspublic 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>();
}
}
Global.asax.cspublic 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();
}
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
Go to sentry.io/settings/auth-tokens/ and create a token with project:releases and org:read scopes.
Step 2: Add MSBuild properties to.csproj or Directory.Build.props:
<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: SetSENTRY_AUTH_TOKEN in CI:
# GitHub Actions
- name: Build & upload symbols
run: dotnet build -c Release
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
Load the corresponding reference file and follow its steps:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | references/error-monitoring.md | Always — CaptureException, scopes, enrichment, filtering |
| Tracing | references/tracing.md | Server apps, distributed tracing, EF Core spans, custom instrumentation |
| Profiling | references/profiling.md | Performance-critical apps on .NET 6+ |
| Logging | references/logging.md | ILogger<T>, Serilog, NLog, log4net integration |
For each feature: read the reference file, follow its steps exactly, and verify before moving on.
After wizard or manual setup, add a test throw and remove it after verifying:
// 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 ILogger, check it appears as Sentry breadcrumb |
| Symbol upload working | Stack trace shows Controllers/HomeController.cs:42 not <unknown> |
SentryOptions| Option | Type | Default | Env Var | Notes |
|---|---|---|---|---|
Dsn | string | — | SENTRY_DSN | Required. SDK disabled if unset. |
Debug | bool | false | — | SDK diagnostic output. Disable in production. |
SentryAspNetCoreOptions)| Option | Type | Default | Notes |
|---|---|---|---|
MaxRequestBodySize | RequestSize | None | None, Small (~4 KB), Medium (~10 KB), Always |
MinimumBreadcrumbLevel |
SentryMauiOptions)| Option | Type | Default | Notes |
|---|---|---|---|
IncludeTextInBreadcrumbs | bool | false | Text from Button, Label, Entry elements. ⚠️ PII risk. |
IncludeTitleInBreadcrumbs | bool |
| Variable | Purpose |
|---|---|
SENTRY_DSN | Project DSN |
SENTRY_RELEASE | App version (e.g. my-app@1.2.3) |
SENTRY_ENVIRONMENT | Deployment environment name |
SENTRY_AUTH_TOKEN | MSBuild / sentry-cli symbol upload auth token |
ASP.NET Core: use double underscore __ as hierarchy separator:
export Sentry__Dsn="https://..."
export Sentry__TracesSampleRate="0.1"
| Property | Type | Default | Description |
|---|---|---|---|
SentryOrg | string | — | Sentry organization slug |
SentryProject | string | — | Sentry project slug |
SentryUploadSymbols | bool | false |
After completing .NET setup, check for companion frontend projects:
# Check for frontend in adjacent directories
ls ../frontend ../client ../web ../app 2>/dev/null
# Check for JavaScript framework indicators
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/ |
| Vue.js | @sentry/vue — see docs.sentry.io/platforms/javascript/guides/vue/ |
Connecting frontend and backend with the same Sentry project enables distributed tracing — a single trace view spanning browser, .NET server, and any downstream APIs.
| Issue | Cause | Solution |
|---|---|---|
| Events not appearing | DSN misconfigured | Set Debug = true and check console output for SDK diagnostic messages |
| Stack traces show no file/line | PDB files not uploaded | Add SentryUploadSymbols=true to .csproj; set SENTRY_AUTH_TOKEN in CI |
| WPF/WinForms exceptions missing | IsGlobalModeEnabled not set | Set options.IsGlobalModeEnabled = true in |
Weekly Installs
167
Repository
GitHub Stars
82
First Seen
Mar 1, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex166
gemini-cli163
cursor163
kimi-cli162
github-copilot162
amp162
Electron应用自动化指南:使用agent-browser通过CDP实现桌面应用自动化
13,200 周安装
Loom视频转录获取器 - 自动提取Loom视频字幕与文本,支持GraphQL API
163 周安装
bioRxiv数据库Python工具:高效搜索下载预印本,支持关键词/作者/日期/类别筛选
163 周安装
Magento 2 Hyvä CMS 组件创建器 - 快速构建自定义CMS组件
163 周安装
项目文档协调器 - 自动化文档生成与上下文管理工具
163 周安装
GPUI 布局与样式:Rust 类型安全的 CSS 样式库,Flexbox 布局与链式 API
163 周安装
Telegram自动化指南:通过Rube MCP与Composio实现消息发送、聊天管理
163 周安装
| Frontend directory found? | Trigger Phase 4 cross-link |
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 |
| Crons | references/crons.md | Hangfire, Quartz.NET, or scheduled function monitoring |
DiagnosticLevel |
SentryLevel |
Debug |
| — |
Debug, Info, Warning, Error, Fatal |
Release | string | auto | SENTRY_RELEASE | Auto-detected from assembly version + git SHA |
Environment | string | "production" | SENTRY_ENVIRONMENT | "debug" when debugger attached |
Dist | string | — | — | Build variant. Max 64 chars. |
SampleRate | float | 1.0 | — | Error event sampling rate 0.0–1.0 |
TracesSampleRate | double | 0.0 | — | Transaction sampling. Must be > 0 to enable. |
TracesSampler | Func<SamplingContext, double> | — | — | Per-transaction dynamic sampler; overrides TracesSampleRate |
ProfilesSampleRate | double | 0.0 | — | Fraction of traced transactions to profile. Requires Sentry.Profiling. |
SendDefaultPii | bool | false | — | Include user IP, name, email |
AttachStacktrace | bool | true | — | Attach stack trace to all messages |
MaxBreadcrumbs | int | 100 | — | Max breadcrumbs stored per event |
IsGlobalModeEnabled | bool | false* | — | *Auto-true for MAUI, Blazor WASM. Must be true for WPF, WinForms, Console. |
AutoSessionTracking | bool | false* | — | *Auto-true for MAUI. Enable for Release Health. |
CaptureFailedRequests | bool | true | — | Auto-capture HTTP client errors |
CacheDirectoryPath | string | — | — | Offline event caching directory |
ShutdownTimeout | TimeSpan | — | — | Max wait for event flush on shutdown |
HttpProxy | string | — | — | Proxy URL for Sentry requests |
EnableBackpressureHandling | bool | true | — | Auto-reduce sample rates on delivery failures |
LogLevel |
Information |
| Min log level for breadcrumbs |
MinimumEventLevel | LogLevel | Error | Min log level to send as Sentry event |
CaptureBlockingCalls | bool | false | Detect .Wait() / .Result threadpool starvation |
FlushOnCompletedRequest | bool | false | Required for Lambda / serverless |
IncludeActivityData | bool | false | Capture System.Diagnostics.Activity values |
false |
Titles from Window, Page elements. ⚠️ PII risk. |
IncludeBackgroundingStateInBreadcrumbs | bool | false | Window.Backgrounding event state. ⚠️ PII risk. |
| Upload PDB files for line numbers in stack traces |
SentryUploadSources | bool | false | Upload source files for source context |
SentryCreateRelease | bool | false | Auto-create a Sentry release during build |
SentrySetCommits | bool | false | Associate git commits with the release |
SentryUrl | string | — | Self-hosted Sentry URL |
| Nuxt | @sentry/nuxt — see docs.sentry.io/platforms/javascript/guides/nuxt/ |
SentrySdk.Init()| Lambda/serverless events lost | Container freezes before flush | Set options.FlushOnCompletedRequest = true |
| WPF UI-thread exceptions missing | DispatcherUnhandledException not wired | Register App.DispatcherUnhandledException in constructor (not OnStartup) |
| Duplicate HTTP spans in Azure Functions | Both Sentry and OTel instrument HTTP | Set options.DisableSentryHttpMessageHandler = true |
TracesSampleRate has no effect | Rate is 0.0 (default) | Set TracesSampleRate > 0 to enable tracing |
appsettings.json values ignored | Config key format wrong | Use flat key "Sentry:Dsn" or env var Sentry__Dsn (double underscore) |
BeforeSend drops all events | Hook returns null unconditionally | Verify your filter logic; return null only for events you want to drop |
| MAUI native crashes not captured | Wrong package | Confirm Sentry.Maui is installed (not just Sentry) |