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

标签 c# asp.net-core design-patterns interface serilog

你好,我正在开发一个 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/

相关文章:

c# - 动态显示 Razor ValidationMessageFor

c# - 如何在后面的代码中使字符串加粗

c# - 从 appSettings.json 获取值(value)?

java - 急切初始化单例 vs 惰性初始化单例

c# - 无法通过 TCP 连接到同一程序的其他实例

c# - Restsharp:IRestResponse内容返回 "[]"

c# - SignInManager IsSignedIn 在 SignalR 集线器中返回 false

c# - 从 SWT token 获取 claim

java - 消息传递对象设计的 OOP 建议

php - 在 MVC 应用程序中从 Model 正确调用数据库?