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

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

System.Diagnostics.DiagnosticSource 通過訂閱發佈模式運行,我們可以根據自己地需要發現數據源並訂閱感興趣的數據源。

 

DiagnosticSource 與 ILogger 區別

一般來說,DiagnosticSource主要強類型診斷,它可以記錄諸如"Microsoft.AspNetCore.Mvc.ViewNotFound"之類的事件。

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

 

示例

添加必要的依賴項

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

<PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="3.1.32" />

 

發出Event

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

private readonly ILogger<WeatherForecastController> _logger;
private readonly DiagnosticSource _diagnosticSource;
const string DKEY = "Invoke_WeatherForecast";
public WeatherForecastController(ILogger<WeatherForecastController> logger, DiagnosticSource diagnosticSource)
{
    _logger = logger;
    _diagnosticSource = diagnosticSource;
}

[HttpGet]
public string Get()
{
    if (_diagnosticSource.IsEnabled(DKEY))
    {
        _diagnosticSource.Write(DKEY,
            new
            {
                time = DateTime.Now,
                data = "ttt"
            });
    }
    return "OK";
}

 

定義Listener

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

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

public class DemoDiagnosticListener
{
    const string DKEY = "Invoke_WeatherForecast";
    [DiagnosticName(DKEY)]
    public virtual void CallWeatherForecast (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();

 

效果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章