我正在尝试通过执行以下操作来记录传递给 Controller 的模型:
_log
.ForContext("Id", "XXXXXX-XXXX-XXXX-XXXXXXXXX")
.ForContext("Email", email)
.ForContext("UserId", userId)
.ForContext("Parameters", parameters)
.ForContext("Errors", errors.ToArray())
.ForContext("ActionArguments", actionArguments)
.Information(message);
哪里actionArguments
类型为 IDictionary<string, object> actionArguments
.这被解释为{
someProperty: "Some.Namespace.Dtos.Something.MyTypeDto"
}
我真的希望someProperty
扩展到复杂类型所代表的内容。是否可以?怎么做?
最佳答案
默认情况下,Serilog 将通过调用 ToString()
序列化它不理解的类型(包括您自己的自定义类型)的对象。得到一个简单的表示。 ToString()
的默认实现对于一个对象只返回类型的全名,这就是为什么你的 DTO 的类型名称出现在日志上下文中。
你所追求的在 Serilog 中被称为“解构”。在 documentation ,这被定义为:
Destructuring is the process of taking a complex .NET object and converting it into a structure, which may later be represented as say, a JSON object or XML blob
有一个可选参数
destructureObjects
您可以提供给 ILogger.ForContext
告诉 Serilog 尝试从对象中提取附加信息的方法: .ForContext("ActionArguments", actionArguments, destructureObjects: true)
默认情况下,它将使用反射递归地解构,有效地遍历对象的所有属性和这些属性的任何属性等,直到找到知道如何格式化的类型。请注意不要使用这种方法记录任何敏感信息; Serilog 将尽最大努力包含它找到的每个值。
关于c# - Serilog - ForContext 将字典值视为复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63573838/