C# 如何在深度调用中使用serilog跟踪请求

C# 如何在深度调用中使用serilog跟踪请求,c#,asp.net-core,design-patterns,interface,serilog,C#,Asp.net Core,Design Patterns,Interface,Serilog,您好,我正在开发一个ASP NET核心应用程序,在设计接口时遇到问题。我正在使用serilog,当一个请求进入控制器时,它会得到一个GUID。我试图找到一种优雅的方法来跟踪调用中的各个请求,而不在我的所有请求中包含此GUID接口 public interface IService { Task GetSomething(string corellationId); //how do i get rid of this id } public interface ISomeOtherSe

您好,我正在开发一个
ASP NET核心应用程序
,在设计接口时遇到问题。我正在使用
serilog
,当一个请求进入控制器时,它会得到一个
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);
   }
}
如您所见,如果我有一些深层调用,我需要更改所有接口,以便它们都包括
corelationid
,这是请求进入我的控制器时设置的
GUID


是否有任何方法可以在整个调用过程中跟踪单个请求,而无需将此
GUID
从一层传递到另一层?

您可以使用
LogContext.PushProperty
-这在引擎盖下使用
AsyncLocal
,因此多线程场景不受关注。
有关更多信息,请在调用时检查此

,并在您的
日志配置
上检查
丰富.FromLogContext()
,然后ASP.NET Core将为每个请求分配一个(有效的)GUID
RequestId
属性,该属性将自动附加到请求期间引发的所有事件,包括在深度调用中。

可能有帮助吗?问题不是识别它。问题在于将它深入传递到调用中,这些调用可能在其他程序集等中,以便在日志中查看该请求停止的位置(如果失败)。