gpt4 book ai didi

c# - Serilog 序列化字段

转载 作者:行者123 更新时间:2023-11-30 14:47:14 25 4
gpt4 key购买 nike

如果我有以下类(class)

public class Customer
{
public string Name;
}

然后在Serilog中有如下日志命令

Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.Seq("http://localhost:5341")
.CreateLogger();

var item = new Customer();
item.Name = "John";
Serilog.Log.Information("Customer {@item}", item);

日志只是在 Seq 中显示为

Customer {}

如果我将 Name 字段更改为一个属性,它会起作用,但我不想在这个阶段这样做。有什么解决办法吗?

最佳答案

要仅针对一种类型执行此操作(推荐),您可以使用:

.Destructure.ByTransforming<Customer>(c => new { c.Name })

如果你想包含所有类型的公共(public)字段,或者那些匹配某种条件的公共(public)字段,你可以插入一个策略来实现:

class IncludePublicFieldsPolicy : IDestructuringPolicy
{
public bool TryDestructure(
object value,
ILogEventPropertyValueFactory propertyValueFactory,
out LogEventPropertyValue result)
{
if (!(value is SomeBaseType))
{
result = null;
return false;
}

var fieldsWithValues = value.GetType().GetTypeInfo().DeclaredFields
.Where(f => f.IsPublic)
.Select(f => new LogEventProperty(f.Name,
propertyValueFactory.CreatePropertyValue(f.GetValue(value))));

result = new StructureValue(fieldsWithValues);
return true;
}
}

该示例将其范围缩小为仅查看从 SomeBaseType 派生的对象。

您可以将其插入:

.Destructure.With<IncludePublicFieldsPolicy>()

(我认为这可能需要一些调整,但应该是一个很好的起点。)

关于c# - Serilog 序列化字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com