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

效果

64be09c27d671a68bf83a9e13c969d0b.png

关注我获取技术分享

bc226d4806a835c41887043d58f9e05e.jpeg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值