I am trying to add dynamic custom properties to Serilog, but I am not sure how to do it the way I want. Here is the code:
if (data.Exception != null)
{
_logger.ForContext("Exception", data.Exception, true);
}
await Task.Run(() =>
_logger.ForContext("User", _loggedUser.Id)
.Information(ControllerActionsFormat.RequestId_ExecutedAction, data.RequestId, data.ActionName)
);
but the Exception property is not being persisted. I have tried:
await Task.Run(() =>
_logger.ForContext("Exception", data.Exception, true)
.ForContext("User", _loggedUser.Id)
.Information(ControllerActionsFormat.RequestId_ExecutedAction, data.RequestId, data.ActionName)
);
and it works fine, but sometimes I have to treat the data before I can use it (like iterating a dictionary containing a method's parameters). I am open to ideas.
What you're missing in your first example is keeping track of the logger returned from
ForContext()
. @BrianMacKay's example is one way to do this, but you can also do it in place like so: