Serilog ForContext and Custom Properties

断了今生、忘了曾经 提交于 2019-12-06 02:11:56

问题


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.


回答1:


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));



回答2:


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.



来源:https://stackoverflow.com/questions/30915733/serilog-forcontext-and-custom-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!