5

我正在尝试将动态自定义属性添加到 Serilog,但我不确定如何按照我想要的方式进行操作。这是代码:

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

但 Exception 属性没有被持久化。我努力了:

            await Task.Run(() =>
            _logger.ForContext("Exception", data.Exception, true)
                .ForContext("User", _loggedUser.Id)
                .Information(ControllerActionsFormat.RequestId_ExecutedAction, data.RequestId, data.ActionName)
            );

它工作正常,但有时我必须先处理数据才能使用它(比如迭代包含方法参数的字典)。我对想法持开放态度。

4

2 回答 2

4

您在第一个示例中缺少的是跟踪从ForContext(). @BrianMacKay 的示例是执行此操作的一种方法,但您也可以像这样就地执行此操作:

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));
于 2015-06-18T22:08:01.970 回答
3

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.

于 2015-06-18T13:49:55.707 回答