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 readonlyDiagnosticSource _diagnosticSource;const string DKEY = "Invoke_WeatherForecast";public WeatherForecastController(ILogger<WeatherForecastController>logger, DiagnosticSource diagnosticSource)
{
_logger
=logger;
_diagnosticSource
=diagnosticSource;
}

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

定义Listener

有多种方法可以创建使用DiagnosticSource事件的Listener,但最简单的方法之一是使用Microsoft.Extensions.DiagnosticAdapter包提供的功能。

要创建侦听器,您可以创建一个类。然后,您可以使用属性来装饰该方法[DiagnosticName],并提供要侦听的事件名称:

public classDemoDiagnosticListener
{
const string DKEY = "Invoke_WeatherForecast";
[DiagnosticName(DKEY)]
public virtual void CallWeatherForecast (DateTime time, stringdata)
{
Console.WriteLine($
"WeatherForecast called: {time} {data}");
}
}

启动监听

剩下的就是在Program.cs中启动监听

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

...

app.Run();

效果

标签: none

添加新评论