2017-09-11 47 views
2

如果我有下面的類Serilog序列化領域

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

日誌只是顯示在序列作爲

Customer {} 

如果我將名稱字段更改爲它的工作屬性,但在此階段我不希望這樣做。有沒有辦法解決它?

+0

一種選擇可能是使用了''解構''LoggerConfiguration''上的配置對象,如下所述:https://github.com/serilog/serilog/wiki/Structured-Data#customizing-the-stored-data –

+0

當'Name'屬性時它工作嗎? – ASpirin

+0

是的,如果我讓Name成爲它的作品。 – Craig

回答

2

要只爲一個類型(推薦)做到這一點,你可以使用:

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

如果要包括所有類型的公共領域,或那些符合某種條件下,你可以插入政策做:

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

(我認爲這是可能需要一些調整,但應該是一個很好的起點。)

+1

作品完美,謝謝。 – Craig