sentry-dotnet-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sentry .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
    ,
    Sentry.AspNetCore
    , or
    Sentry.Maui
  • User wants to capture unhandled exceptions in WPF, WinForms, MAUI, or Azure Functions
  • User asks about
    SentryOptions
    ,
    BeforeSend
    ,
    TracesSampleRate
    , or symbol upload
Note: SDK version and APIs below reflect
Sentry
NuGet packages ≥6.1.0. Always verify against docs.sentry.io/platforms/dotnet/ before implementing.

  • 用户要求「给.NET添加Sentry」、「在C#中配置Sentry」或「为ASP.NET Core安装Sentry」
  • 用户需要为.NET应用配置错误监控、链路追踪、性能剖析、日志记录或定时任务监控
  • 用户提到
    SentrySdk.Init
    UseSentry
    Sentry.AspNetCore
    Sentry.Maui
  • 用户需要在WPF、WinForms、MAUI或Azure Functions中捕获未处理异常
  • 用户询问
    SentryOptions
    BeforeSend
    TracesSampleRate
    或符号上传相关问题
注意: 下方的SDK版本和API对应≥6.1.0版本的
Sentry
NuGet包。 实施前请始终参考 docs.sentry.io/platforms/dotnet/ 确认最新规范。

Phase 1: Detect

阶段1:项目检测

Run these commands to understand the project before making any recommendations:
bash
undefined
在给出任何推荐方案前,先运行以下命令了解项目信息:
bash
undefined

Detect 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:
FeatureRecommend when...
Error MonitoringAlways — non-negotiable baseline
TracingAlways for ASP.NET Core — request traces, EF Core spans, HttpClient spans are high-value
LoggingApp uses
ILogger<T>
, Serilog, NLog, or log4net
ProfilingPerformance-critical service on .NET 6+
CronsApp 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价值很高
日志集成应用使用
ILogger<T>
、Serilog、NLog或log4net时
性能剖析运行在.NET 6+的性能敏感服务
定时任务监控应用使用Hangfire、Quartz.NET或定时Azure Functions时
推荐话术:「我建议配置错误监控+链路追踪+日志集成,需要我额外添加性能剖析或定时任务监控吗?」

Phase 3: Guide

阶段3:配置指引

Option 1: Wizard (Recommended)

方案1:向导配置(推荐)

bash
npx @sentry/wizard@latest -i dotnet
The 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
undefined
bash
undefined

ASP.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

ASP.NET Core —
Program.cs

csharp
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.json
(alternative configuration):
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"
  }
}
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.json
(替代配置方式):
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"
  }
}
环境变量配置(使用双下划线作为分隔符):
bash
export SENTRY__Dsn="https://examplePublicKey@o0.ingest.sentry.io/0"
export SENTRY__TracesSampleRate="0.1"
export SENTRY__Environment="staging"

WPF —
App.xaml.cs

WPF —
App.xaml.cs

⚠️ Critical: Initialize in the constructor, NOT in
OnStartup()
. The constructor fires earlier, catching more failure modes.
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

WinForms —
Program.cs

csharp
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

.NET MAUI —
MauiProgram.cs

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-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

Blazor WebAssembly —
Program.cs

csharp
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

Azure Functions (隔离工作进程) —
Program.cs

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()                        // 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

AWS Lambda —
LambdaEntryPoint.cs

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; // 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

传统ASP.NET —
Global.asax.cs

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 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
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
:
xml
<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
SENTRY_AUTH_TOKEN
in CI:
yaml
undefined
如果没有调试符号,堆栈跟踪只会显示方法名,没有文件名和行号。上传PDB文件可以解锁完整的源码上下文。
步骤1:创建Sentry授权令牌
访问 sentry.io/settings/auth-tokens/ 创建一个拥有
project:releases
org:read
权限的令牌。
步骤2:在
.csproj
Directory.Build.props
中添加MSBuild属性:
xml
<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
yaml
undefined

GitHub 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:
FeatureReference fileLoad 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
Crons
references/crons.md
Hangfire, Quartz.NET, or scheduled function monitoring
For each feature: read the reference file, follow its steps exactly, and verify before moving on.

加载对应的参考文件并严格按照步骤操作:
功能参考文件触发场景
错误监控
references/error-monitoring.md
始终加载 — 包含
CaptureException
、上下文、信息丰富、过滤相关内容
链路追踪
references/tracing.md
服务端应用、分布式追踪、EF Core span、自定义埋点场景
性能剖析
references/profiling.md
运行在.NET 6+的性能敏感应用
日志集成
references/logging.md
ILogger<T>
、Serilog、NLog、log4net集成场景
定时任务监控
references/crons.md
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:
CheckHow
Exceptions capturedThrow a test exception, verify in Sentry Issues
Stack traces readableCheck that file names and line numbers appear
Tracing activeCheck Performance tab for transactions
Logging wiredLog an error via
ILogger
, check it appears as Sentry breadcrumb
Symbol upload workingStack trace shows
Controllers/HomeController.cs:42
not
<unknown>

通过向导或手动配置完成后,添加一个测试异常,验证通过后再删除:
csharp
// ASP.NET Core:添加一个临时端点
app.MapGet("/sentry-test", () =>
{
    throw new Exception("Sentry测试异常 — 请删除我");
});

// 或在任意位置主动上报
SentrySdk.CaptureException(new Exception("Sentry测试异常 — 请删除我"));
然后检查你的Sentry问题面板 — 异常应该会在30秒内出现。
验证清单:
检查项验证方式
异常已捕获抛出测试异常,在Sentry问题面板中确认存在
堆栈跟踪可读检查是否显示文件名和行号
链路追踪已启用检查性能面板是否存在事务
日志已接入通过
ILogger
打印一条错误日志,确认它作为Sentry面包屑出现
符号上传正常堆栈跟踪显示
Controllers/HomeController.cs:42
而非
<unknown>

Config Reference

配置参考

Core
SentryOptions

核心
SentryOptions

OptionTypeDefaultEnv VarNotes
Dsn
string
SENTRY_DSN
Required. SDK disabled if unset.
Debug
bool
false
SDK diagnostic output. Disable in production.
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
配置项类型默认值环境变量说明
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、控制台应用必须设为
true
AutoSessionTracking
bool
false
*
*MAUI自动设为
true
。启用后可统计发布健康度。
CaptureFailedRequests
bool
true
自动捕获HTTP客户端错误
CacheDirectoryPath
string
离线事件缓存目录
ShutdownTimeout
TimeSpan
关闭时等待事件上报的最长时间
HttpProxy
string
Sentry请求的代理URL
EnableBackpressureHandling
bool
true
上报失败时自动降低采样率

ASP.NET Core Extended Options (
SentryAspNetCoreOptions
)

ASP.NET Core扩展配置(
SentryAspNetCoreOptions

OptionTypeDefaultNotes
MaxRequestBodySize
RequestSize
None
None
,
Small
(~4 KB),
Medium
(~10 KB),
Always
MinimumBreadcrumbLevel
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
配置项类型默认值说明
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
的值

MAUI Extended Options (
SentryMauiOptions
)

MAUI扩展配置(
SentryMauiOptions

OptionTypeDefaultNotes
IncludeTextInBreadcrumbs
bool
false
Text from
Button
,
Label
,
Entry
elements. ⚠️ PII risk.
IncludeTitleInBreadcrumbs
bool
false
Titles from
Window
,
Page
elements. ⚠️ PII risk.
IncludeBackgroundingStateInBreadcrumbs
bool
false
Window.Backgrounding
event state. ⚠️ PII risk.
配置项类型默认值说明
IncludeTextInBreadcrumbs
bool
false
来自
Button
Label
Entry
元素的文本。⚠️ 存在PII泄露风险。
IncludeTitleInBreadcrumbs
bool
false
来自
Window
Page
元素的标题。⚠️ 存在PII泄露风险。
IncludeBackgroundingStateInBreadcrumbs
bool
false
Window.Backgrounding
事件状态。⚠️ 存在PII泄露风险。

Environment Variables

环境变量

VariablePurpose
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:
bash
export Sentry__Dsn="https://..."
export Sentry__TracesSampleRate="0.1"
变量用途
SENTRY_DSN
项目DSN
SENTRY_RELEASE
应用版本(例如
my-app@1.2.3
SENTRY_ENVIRONMENT
部署环境名称
SENTRY_AUTH_TOKEN
MSBuild /
sentry-cli
符号上传的授权令牌
ASP.NET Core: 使用双下划线
__
作为层级分隔符:
bash
export SENTRY__Dsn="https://..."
export SENTRY__TracesSampleRate="0.1"

MSBuild Symbol Upload Properties

MSBuild符号上传属性

PropertyTypeDefaultDescription
SentryOrg
string
Sentry organization slug
SentryProject
string
Sentry project slug
SentryUploadSymbols
bool
false
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

属性类型默认值描述
SentryOrg
string
Sentry组织标识
SentryProject
string
Sentry项目标识
SentryUploadSymbols
bool
false
上传PDB文件,用于显示堆栈跟踪的行号
SentryUploadSources
bool
false
上传源文件,用于展示源码上下文
SentryCreateRelease
bool
false
构建时自动创建Sentry版本
SentrySetCommits
bool
false
将git提交与版本关联
SentryUrl
string
自托管Sentry的URL

Phase 4: Cross-Link

阶段4:跨端关联

After completing .NET setup, check for companion frontend projects:
bash
undefined
完成.NET配置后,检查是否存在配套的前端项目:
bash
undefined

Check 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

问题排查

IssueCauseSolution
Events not appearingDSN misconfiguredSet
Debug = true
and check console output for SDK diagnostic messages
Stack traces show no file/linePDB files not uploadedAdd
SentryUploadSymbols=true
to
.csproj
; set
SENTRY_AUTH_TOKEN
in CI
WPF/WinForms exceptions missing
IsGlobalModeEnabled
not set
Set
options.IsGlobalModeEnabled = true
in
SentrySdk.Init()
Lambda/serverless events lostContainer freezes before flushSet
options.FlushOnCompletedRequest = true
WPF UI-thread exceptions missing
DispatcherUnhandledException
not wired
Register
App.DispatcherUnhandledException
in constructor (not
OnStartup
)
Duplicate HTTP spans in Azure FunctionsBoth Sentry and OTel instrument HTTPSet
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 wrongUse 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 capturedWrong packageConfirm
Sentry.Maui
is installed (not just
Sentry
)
问题原因解决方案
事件未出现DSN配置错误设置
Debug = true
,查看控制台的SDK诊断日志
堆栈跟踪没有显示文件/行号未上传PDB文件
.csproj
中添加
SentryUploadSymbols=true
;在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 spanSentry和OTel都对HTTP做了埋点设置
options.DisableSentryHttpMessageHandler = true
TracesSampleRate
不生效
采样率为默认值
0.0
设置
TracesSampleRate > 0
启用链路追踪
appsettings.json
配置不生效
配置键格式错误使用扁平化键
"Sentry:Dsn"
或环境变量
SENTRY__Dsn
(双下划线)
BeforeSend
丢弃了所有事件
钩子无条件返回
null
检查过滤逻辑;仅对需要丢弃的事件返回
null
MAUI原生崩溃未捕获安装的包不正确确认安装的是
Sentry.Maui
(而非仅
Sentry