How to write a complex object using Serilog to a valid json format?

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 the following line for logging:

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

I get the 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 invalid json. "LogRequestParameters" (class name) comes at the beginning. "Request" (property name) goes twice. How can I register valid json?

+4
source share
1 answer

Assuming you are using a file, a sliding file, or console receivers, you need to specify JsonFormatter:

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

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

+4

Source: https://habr.com/ru/post/1656094/


All Articles