Serilog不会产生预期的json

时间:2015-02-11 06:11:51

标签: c# json serilog

我有以下代码。

Serilog.ILogger logger = Serilog.Log.Logger;
logger = new LoggerConfiguration()
   .WriteTo.Sink(new FileSink(@"c:\temp\mylogs.txt", new JsonFormatter(), null)).MinimumLevel.Debug() 
   .CreateLogger();
var newType = new MyType() { Game = "Poker", HasValue = false, Name = "Dave", TimeOfEntry = DateTime.Now.AddDays(-1) };
logger.Debug("This is the new type {NewType} generated at {Time}", newType, DateTime.Now);

日志文件显示如下

{"Timestamp":"2015-02-11T00:53:51.8501574-05:00","Level":"Debug","MessageTemplate":"This is the new type {NewType} generated at {Time}","Properties":{"NewType":"ConsoleTestApp.MyType","Time":"2015-02-11T00:53:51.8491563-05:00"}}

在日志文件输出中没有意义的部分是:

{"NewType":"ConsoleTestApp.MyType", ...

我期待这样的事情。

{"NewType": {Game = "Poker", HasValue = false, Name = "Dave", ...

我做错了吗?

1 个答案:

答案 0 :(得分:8)

默认情况下,Serilog会ToString()传递给消息模板的任何未知类型。

激活Serilog所称的" destructuring" (即序列化)您需要在属性名称前添加一个符号@

logger.Debug("This is the new type {@NewType} generated at {Time}", newType, DateTime.Now);