[英]Serilog ForContext and Custom Properties
I am trying to add dynamic custom properties to Serilog, but I am not sure how to do it the way I want. 我正在尝试向Serilog添加动态自定义属性,但我不确定如何以我想要的方式执行此操作。 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. 但是Exception属性没有被持久化。 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()
. 您在第一个示例中缺少的是跟踪从
ForContext()
返回的记录器。 @BrianMacKay's example is one way to do this, but you can also do it in place like so: @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));
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. 我没有对此进行测试,但它应该与链接一堆.ForContext()调用相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.