如何在深层调用中使用serilog跟踪请求

Ber*_*ian 2 c# design-patterns interface serilog asp.net-core

您好,我在ASP NET Core application设计接口时遇到了问题。我正在使用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);
   }
}
Run Code Online (Sandbox Code Playgroud)

正如你可以看到,如果我有一些深层次的电话我需要改变所有接口,使它们都包含corellationId这是GUID当请求进入我的控制器设置。

有什么方法可以在整个调用过程中跟踪单个请求,而又不会在各个GUID层之间传递?

vas*_*ski 6

You can use LogContext.PushProperty - this uses AsyncLocal under the hood so multi-threaded scenario is no concern. For more info check this link