如果我有以下类(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/