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:
var logger = _logger;
if (data.Exception != null)
{
   logger = logger.ForContext("Exception", data.Exception, true);
}
await Task.Run(() =>
    logger.ForContext("User", _loggedUser.Id)
          .Information(ControllerActionsFormat.RequestId_ExecutedAction,
                       data.RequestId, data.ActionName));
                        If you're saying that you need to iterate a key/value pair and add a property for each entry, and that there's no way to know what these entries are ahead of time, I suppose you could try something like this:
var dictionary = new Dictionary<string, string>();
var logger = new LoggerConfiguration().CreateLogger();
foreach (var key in dictionary.Keys)
{
    logger = logger.ForContext(key, dictionary[key]);
}
return logger;
I didn't test this, but it should be the same as chaining a bunch of .ForContext() calls.
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