當前位置: 妍妍網 > 碼農

.Net Core中使用DiagnosticSource進行日誌記錄

2024-03-13碼農

System.Diagnostics.DiagnosticSource 可以豐富地記錄程式中地日誌,包括不可序列化的型別(例如 HttpResponseMessage 或 HttpContext)。

System.Diagnostics.DiagnosticSource 透過訂閱發 布模式執行,我們可以根據自己地需要發現資料來源並訂閱感興趣的資料來源。

DiagnosticSource 與 ILogger 區別

DiagnosticSource主要用於強型別診斷, 它可以記錄諸如 "Microsoft.AspNetCore.Mvc.ViewNotFound" 之類的事件。


而ILogger用於記錄更具體的資訊,例如"Executing JsonResult, writing value {Value}。

範例

添加必要的依賴項

我們首先將需要的 NuGet 包添加到我們的project中

<PackageReferenceInclude="Microsoft.Extensions.DiagnosticAdapter"Version="3.1.32" />

發出Event

首先需要註入DiagnosticSource, 然後透過其write方法發出Event

privatereadonly ILogger<WeatherForecastController> _logger;privatereadonly DiagnosticSource _diagnosticSource;conststring DKEY = "Invoke_WeatherForecast";publicWeatherForecastController(ILogger<WeatherForecastController> logger, DiagnosticSource diagnosticSource){ _logger = logger; _diagnosticSource = diagnosticSource;}[HttpGet]publicstringGet(){if (_diagnosticSource.IsEnabled(DKEY)) { _diagnosticSource.Write(DKEY,new { time = DateTime.Now, data = "ttt" }); }return"OK";}

定義Listener

有多種方法可以建立使用DiagnosticSource事件的Listener,但最簡單的方法之一是使用Microsoft.Extensions.DiagnosticAdapter包提供的功能。

要建立偵聽器,您可以建立一個類。然後,您可以使用內容來裝飾該方法[DiagnosticName],並提供要偵聽的事件名稱:

public classDemoDiagnosticListener{conststring DKEY = "Invoke_WeatherForecast"; [DiagnosticName(DKEY)]publicvirtualvoidCallWeatherForecast (DateTime time, string data) { Console.WriteLine($"WeatherForecast called: {time}{data}"); }}

啟動監聽

剩下的就是在Program.cs中啟動監聽

var app = builder.Build();var diagnosticListener = app.Services.GetRequiredService<DiagnosticListener>();var listener = new DemoDiagnosticListener();diagnosticListener.SubscribeWithAdapter(listener);...app.Run();

效果

關註我獲取技術分享