使用 ILogger 的 BeginScope 紀錄連貫的Logger資訊
紀錄Log時,時常會因為多個API請求、非同步請求等各種原因,導致事後查找Log難以找出相同請求的所有Log
這時候可以使用ILogger提供的方法 BeginScope 建立一個範圍,並且給範圍一個識別碼,以利之後的排查
1.範例使用Console作為Provider,先在Startup上加上它
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddLogging(builder =>
{
builder.AddConsole();
});
}
2.為Controlloer加上一些Log,並且Controller參考了一個Service,也一併紀錄Log
//Controller
public WeatherForecastController(ILogger<WeatherForecastController> logger, MyService service)
{
_logger = logger;
_service = service;
}
[HttpGet]
public string Get()
{
_logger.LogTrace("start get");
var result = _service.Test();
_logger.LogTrace("result={result}", result);
_logger.LogTrace("end get");
return result;
}
//Service
public class MyService
{
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public string Test()
{
_logger.LogTrace("log: test");
return "Test";
}
}
3.調整下appsetting,加上Logger的配置
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
},
"Console": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning"
}
}
},
"AllowedHosts": "*"
}
4.Run起來,記錄到的Log則是在哪個Class底下紀錄到了什麼內容,這樣的問題是,當請求一多、非同步的事情也多,那事後查找Log就變得不便
5.這時候可以加上BeginScope,並且加上一個Guid(或是其他資訊,皆可)
[HttpGet]
public string Get()
{
using (_logger.BeginScope("Scope Id:{id}", Guid.NewGuid().ToString("N")))
{
_logger.LogTrace("start get");
var result = _service.Test();
_logger.LogDebug("result={result}", result);
_logger.LogDebug("end get");
return result;
}
}
6.以及在appsetting的配置中加上 IncludeScopes=true
"Console": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Trace",
"Microsoft": "Warning"
}
}
7.接著啟動應用,可以看到在每個Log的後面都加上了Scope的Message
Microsoft Docs https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
Sample Code https://github.com/ianChen806/LoggerScopeSample