Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track request with serilog in deep calls

Hello i am developing a ASP NET Core application having an issue with designing interfaces.I am using serilog and when a request enters a controller it gets a GUID .I am trying to find an elegant way to track individual requests deep in calls without including this GUID in all my interfaces.

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);
   }
}

As you can see if i have some deep calls i would need to change all interfaces so that they all include the corellationId which is the GUID that was set when the request entered my controller.

Is there any way of tracking individual requests throughout calls without passing this GUID from layer to layer?

like image 890
Bercovici Adrian Avatar asked Dec 23 '22 20:12

Bercovici Adrian


1 Answers

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

like image 151
vasil oreshenski Avatar answered Dec 28 '22 05:12

vasil oreshenski