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?
You can use LogContext.PushProperty
- this uses AsyncLocal
under the hood so multi-threaded scenario is no concern.
For more info check this link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With