How to log complex object using Serilog in valid json format?

user1780538 picture user1780538 · Sep 28, 2016 · Viewed 19.3k times · Source

I have this structure:

public class LogRequestParameters
{
    public string RequestID { get; set; }

    public string Type { get; set; }

    public string Level { get; set; }

    public string DateTime { get; set; }

    public string MachineName { get; set; }

    public Request Request { get; set; }
}

public class Request
{
    public string URLVerb { get; set; }
}

I am writing following line for logging:

Serilog.Log.Information("{@LogRequestParameters}", logRequestParameters);

I am getting following output:

LogRequestParameters { RequestID: "bf14ff78-d553-4749-b2ac-0e5c333e4fce", Type: "Request", Level: "Debug", DateTime: "9/28/2016 3:12:27 PM", MachineName: "DXBKUSHAL", Request: Request { URLVerb: "GET /Violation/UnpaidViolationsSummary" } }

This is not a valid json. "LogRequestParameters" (name of class) is coming in the begining. "Request" (name of the property) is coming twice. How can I log a valid json?

Answer

Nicholas Blumhardt picture Nicholas Blumhardt · Sep 28, 2016

Assuming you are using the file, rolling file or console sinks, you need to specify a JsonFormatter:

Log.Logger = new LoggerConfiguration()
    .WriteTo.RollingFile(new JsonFormatter(), "myapp-{Date}.json")
    .CreateLogger();

A few different JSON formats are supported by Serilog; see this post for discussion of some alternatives.