jack
jack

Reputation: 157

How to customize formatting of destructured types in Serilog

The code below produces the output: [2021-09-05 INFO] Created a customer: Customer {Name="Jack"}.

I have two questions. First, is it possible to remove the space between Customer and {Name="Jack"}? Second, is it possible to remove the double quotes around "Jack".

Thanks for any help!

class Program
{
    public class Customer
    {
        public string Name { get; init; }
    }

    static void Main(string[] args)
    {
        var customer = new Customer {Name = "Jack"};
        var logger = new LoggerConfiguration().WriteTo.Console(outputTemplate:
            "[{Timestamp:yyyy-MM-dd} {Level:u4}] {Message:l}{NewLine}").CreateLogger();
        logger.Information("Created a customer: {@Customer}", customer);
    }
}

Upvotes: 1

Views: 3241

Answers (1)

C. Augusto Proiete
C. Augusto Proiete

Reputation: 27878

The customization of how data gets rendered depends on the sink you're using as it's up to the sink to provide you a way to do that.

In the case of the Console sink, which is the one you're using, there's nothing out-of-the-box that would allow you to customize the console output in that way, but it does allow you to provide a custom ITextFormatter so you can implement your own version of the OutputTemplateRenderer, the formatter used by the Console sink, and format the output the way you want it.

Other examples of formatters are the (CompactJsonFormatter.cs and the RenderedCompactJsonFormatter.cs).

Documentation: https://github.com/serilog/serilog/wiki/Formatting-Output

You might also be interested in using an ExpressionTemplate from Serilog.Expressions

Upvotes: 3

Related Questions