Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serilog does not produce expected json

Tags:

json

c#

serilog

I have following code.

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

The log file shows following

{"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"}}

The part that does not make sense in the log file output is this:

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

I was expecting something like this.

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

Did I do something wrong?

like image 713
SamDevx Avatar asked Feb 11 '15 06:02

SamDevx


1 Answers

By default, Serilog will ToString() any unknown types passed into message templates.

To activate what Serilog calls "destructuring" (i.e. serialization) you need to prepend an at-sign @ to the property name:

logger.Debug("This is the new type {@NewType} generated at {Time}", newType, DateTime.Now);
like image 169
Nicholas Blumhardt Avatar answered Nov 17 '22 00:11

Nicholas Blumhardt