当前位置: 欣欣网 > 码农

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

效果

关注我获取技术分享