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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With