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

 

效果

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。