你好,我正在开发一个 ASP NET Core 应用程序
,在设计接口(interface)时遇到问题。我正在使用 serilog
,当请求进入 Controller 时,它会得到一个 GUID
。我正在尝试找到一种优雅的方式来跟踪调用中的各个请求,而无需在我的所有界面中包含此 GUID
。
public interface IService
{
Task GetSomething(string corellationId); //how do i get rid of this id
}
public interface ISomeOtherService
{
Task DoSomethingElse(string corellationId); //how do i get rid of this id
}
public class SomeController:Controller
{
public IService someService {get;set;}
[HttpGet]
public Task Get()
{
string corellationId=Guid.NewGuid().ToString();
Log.Information($"[{corellationId}] - Request started");
try
{
Log.Information($"[{corellationId}] - Get");
await this.someService.GetSomething(corellationId);
}catch(Exception ex)
{
Log.Error($"[{corellationId}] - Get",ex.Message);
}
}
}
public SomeService:ISomeService
{
private ISomeOtherService service{get;set;}
public GetSomething(corellationId)
{
Log.Information("$[{corellationId}] - GetSomething: ");
this.service.DoSomethingElse(corellationId);
}
}
如您所见,如果我有一些深度调用,我需要更改所有接口(interface),以便它们都包含 corellationId
,这是在请求进入了我的 Controller 。
有没有什么方法可以在整个调用过程中跟踪单个请求,而无需逐层传递此 GUID
?
最佳答案
您可以使用 LogContext.PushProperty
- 这在引擎盖下使用了 AsyncLocal
,因此无需担心多线程 场景。
有关更多信息,请查看此 link
关于c# - 如何在深度调用中使用 serilog 跟踪请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58833441/