C# ASP.NET Core 例外追蹤系統 Sentry 使用示範

Sentry 不太算是集中式日誌處理系統,他專注在追蹤錯誤,使用很少的程式碼就可以在發生錯誤時通知我們,提供詳細的資訊讓我們快速解決問題。

使用示範

先到 Sentry 官網 建立一個專案,專案類型選擇 ASP.NET Core ,輸入專案名稱後點選 Create Project 來建立專案:

專案建立好後會顯示需要使用的程式碼,不過這裡的程式碼和官網文件中示範的不太一樣,我們不會使用這裡的程式碼,只需要複製這裡的連結即可。

在專案中先安裝上面提示的套件:
使用 NuGet 安裝 Sentry.AspNetCore 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package Sentry.AspNetCore
    

在 appsettings.json 中加入以下程式碼,將 Dsn 換成上面我們複製的連結即可:
    
{
  "Sentry": {
    "Dsn": "https://a99f98463fbb041547.ingest.us.sentry.io/4507",
    "SendDefaultPii": true,
    "MaxRequestBodySize": "Always",
    "MinimumBreadcrumbLevel": "Debug",
    "MinimumEventLevel": "Warning",
    "AttachStackTrace": true,
    "Debug": true,
    "DiagnosticLevel": "Error",
    "TracesSampleRate": 1.0
  }
}

    

然後在 Program.cs 中加入下面的程式碼:
    
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseSentry();
    

到這裡就已經成功串接 Sentry 了,非常簡單!

為了要測試,我們建立一個範例的 Controller ,呼叫這個 API 就會拋出一個例外:
    
using Microsoft.AspNetCore.Mvc;


[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    [HttpGet("exception")]
    public IActionResult Get()
    {
        throw new Exception($"This is a test exception {DateTime.Now:hh:mm:ss}");
    }
}
    

在 Sentry 網頁中馬上就會看到出現的例外:

在單個例外資訊中還可以看到觸發的連結、專案版本、詳細的錯誤訊息等

如果有需要還可以連結 GitHub 等程式碼版本控制系統,把程式碼交給他分析,能夠更詳細的分析例外資訊。

參考資料:
sentry.io
Sentry - C# Error and Performance Monitoring
Sentry - ASP.NET Core

留言