Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog ForContext and Custom Properties

Tags:

c#

serilog

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.

like image 943
leosbrf Avatar asked Jun 18 '15 12:06

leosbrf


2 Answers

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));
like image 127
Nicholas Blumhardt Avatar answered Oct 23 '22 16:10

Nicholas Blumhardt


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.

like image 3
Brian MacKay Avatar answered Oct 23 '22 17:10

Brian MacKay