Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 975
user1780538 Avatar asked Sep 28 '16 13:09

user1780538


2 Answers

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.

like image 166
Nicholas Blumhardt Avatar answered Sep 17 '22 15:09

Nicholas Blumhardt


Make sure your Message template includes :lj format specifier at the end:

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(outputTemplate:
        "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
    .CreateLogger();

From documentation:

Message - The log event's message, rendered as plain text. The :l format specifier switches of quoting of strings, and :j uses JSON-style rendering for any embedded structured data.

On front docs page with JSON example there is no mention of it, took plenty of time for me to solve this problem too.

like image 31
Autiarii Avatar answered Sep 16 '22 15:09

Autiarii