- Notifications
You must be signed in to change notification settings - Fork851
Formatting Output
Serilog provides several output formatting mechanisms.
Sinks that write plain text output, such as the console and file-based sinks, generally acceptoutput templates to control how log event data is formatted.
The format of events written by these sinks can be modified using theoutputTemplate configuration parameter. For example, to control theconsole sink:
Log.Logger=newLoggerConfiguration().WriteTo.Console(outputTemplate:"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}").CreateLogger();
A number of built-in properties can appear in output templates:
Exception- The full exception message and stack trace, formatted across multiple lines. Empty if no exception is associated with the event.Level- The log event level, formatted as the full level name. For more compact level names, use a format such as{Level:u3}or{Level:w3}for three-character upper- or lowercase level names, respectively.Message- The log event's message, rendered as plain text. The:lformat specifier switches off quoting of strings, and:juses JSON-style rendering for any embedded structured data.NewLine- A property with the value ofSystem.Environment.NewLine.Properties- All event property values that don't appear elsewhere in the output. Use the:jformat to use JSON rendering.Timestamp- The event's timestamp, as aDateTimeOffset.TraceId- The id of the trace that was active when the event was created, if any.SpanId- The id of the span that was active when the event was created, if any.
Properties from events, including those attached using enrichers, can also appear in the output template.
Many sinks record log events as JSON, or can be configured to do so. To emit JSON, rather than plain text, aformatter can be specified. This example configures thefile sink using the formatter fromSerilog.Formatting.Compact.
Log.Logger=newLoggerConfiguration().WriteTo.File(newCompactJsonFormatter(),"log.txt").CreateLogger();
There are three JSON formatters provided by the Serilog project:
Serilog.Formatting.Json.JsonFormatter- This is the historical default shipped in theSerilog package. It produces a complete rendering of the log event and supports a few configuration options.Serilog.Formatting.Compact.CompactJsonFormatter- A newer, more space-efficient JSON formatter shipped inSerilog.Formatting.Compact.Serilog.Formatting.Compact.RenderedCompactJsonFormatter- Also shipped inSerilog.Formatting.Compact, this formatter pre-rendersmessage templates into text.
TheSerilog.Expressions package includes theExpressionTemplate class formore sophisticated text andJSON formatting. Expression templates can include conditional blocks, repeated sections, computations over event properties, and custom formatting functions.
ExpressionTemplate implementsITextFormatter, so it works with any text-based Serilog sink, includingConsole (with ANSI color themes),File,Debug, andEmail.
Both plain text and JSON formatting are implemented using theITextFormatter interface. Implementations of this interface can format log events into any text-based format.
Custom JSON formatters can be built around theJsonValueFormatter class included in Serilog. For some details seethis blog post.
There are a number of options available to formatting the output of individual types like dates. One example is the use of the format provider that is accepted by most sinks.
Below is a simple console sample using theSerilog.Sinks.Console sink. This is using the default behavior for rendering a date.
classUser{publicintId{get;set;}publicstringName{get;set;}publicDateTimeCreated{get;set;}}publicclassProgram{publicstaticvoidMain(string[]args){Log.Logger=newLoggerConfiguration().WriteTo.Console().CreateLogger();varexampleUser=newUser{Id=1,Name="Adam",Created=DateTime.Now};Log.Information("Created {@User} on {Created}",exampleUser,DateTime.Now);Log.CloseAndFlush();}}
This writes the following output to the console.
[18:46:45 INF] Created {"Id": 1, "Name": "Adam", "Created": "2018-05-17T18:46:45.9064879+10:00", "$type": "User"} on 05/17/2018 18:46:45There may be scenarios where it is desirable to override or specify the way aDateTime is formatted. This can be done via the implementation ofIFormatProvider. This strategy applies to any type that you pass to Serilog.
classUser{publicintId{get;set;}publicstringName{get;set;}publicDateTimeCreated{get;set;}}classCustomDateFormatter:IFormatProvider{readonlyIFormatProviderbasedOn;readonlystringshortDatePattern;publicCustomDateFormatter(stringshortDatePattern,IFormatProviderbasedOn){this.shortDatePattern=shortDatePattern;this.basedOn=basedOn;}publicobjectGetFormat(TypeformatType){if(formatType==typeof(DateTimeFormatInfo)){varbasedOnFormatInfo=(DateTimeFormatInfo)basedOn.GetFormat(formatType);vardateFormatInfo=(DateTimeFormatInfo)basedOnFormatInfo.Clone();dateFormatInfo.ShortDatePattern=this.shortDatePattern;returndateFormatInfo;}returnthis.basedOn.GetFormat(formatType);}}publicclassProgram{publicstaticvoidMain(string[]args){varformatter=newCustomDateFormatter("dd-MMM-yyyy",newCultureInfo("en-AU"));Log.Logger=newLoggerConfiguration().WriteTo.Console(formatProvider:newCultureInfo("en-AU"))// Console 1.WriteTo.Console(formatProvider:formatter)// Console 2.CreateLogger();varexampleUser=newUser{Id=1,Name="Adam",Created=DateTime.Now};Log.Information("Created {@User} on {Created}",exampleUser,DateTime.Now);Log.CloseAndFlush();}}
The following is the output of the above example, with two consoles sinks configured.
[13:57:12 INF] Created {"Id": 1, "Name": "Adam", "Created": "2020-09-01T13:56:59.7803740-05:00", "$type": "User"} on 1/09/2020 1:57:12 PM[13:57:12 INF] Created {"Id": 1, "Name": "Adam", "Created": "2020-09-01T13:56:59.7803740-05:00", "$type": "User"} on 01-Sep-2020 1:57:12 PM