Reputation: 9360
I have a ASP .NET Core
application and i am trying to enrich the Serilog
logger with a property and pass it throghout method calls.
I have used Serilog.Context
to enrich it to no avail, the property is not present in the log.
Program
Log.Logger = new LoggerConfiguration().Enrich.FromLogContext()
.WriteTo.File(logpath)
.CreateLogger();
Controller
public class SomeController{
public ILogger logger=Log.ForContext<SomeController>();
private SomeService Service;
public SomeController(SomeService serv)
{
this.service=serv;
}
[HttpGet]
public async Task DoSomething()
{
string corellationId=Guid.NewGuid().ToString();
LogContext.PushProperty("id",corellationId);
service.Run();
}
}
Service
class SomeService
{
private ILogger logger=Log.ForContext<SomeService>();
public void Run()
{
logger.Information("I AM NOT SEEING the ID from upstream !");
}
}
Basically i want the logs of SomeService
to have the id provided upstream (Controller action).
What i want:
"[id] [value]"+ "[SomeService log]"
P.S The service is injected via dependency injection if it matters.
Upvotes: 6
Views: 15723
Reputation: 61795
You need to use the Properties
token in your outputTemplate
, e.g.
var mt = "{LogLevel:u1}|{SourceContext}|{Message:l}|{Properties}{NewLine}{Exception}"
when you format the output for your sink e.g.:
.WriteTo.File(logpath, outputTemplate: mt)
(ASIDE: You should be using
the LogContext.Push
return value)
Upvotes: 15