5

我有以下代码。

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", ...

我做错什么了吗?

4

1 回答 1

11

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

要激活 Serilog 所谓的“解构”(即序列化),您需要@在属性名称前添加一个 at 符号:

logger.Debug("This is the new type {@NewType} generated at {Time}", newType, DateTime.Now);
于 2015-02-11T21:01:24.437 回答