9

I'm trying to output an enriched property into the rendered message using Serilog:

private static Tester GetTester()
{
    return new Tester {Count = 7, Name = "Redmond"};
}

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .Enrich.WithProperty("Site", "Dan Local")
    .WriteTo
    .ColoredConsole()
    .CreateLogger();

var tester = GetTester();

Log.Verbose("{Site} - This is verbose {@tester}", tester);
Log.Verbose("This is verbose {@tester} - {Site}", tester);

The first log statement outputs:

2014-08-19 10:02:25 [Verbose] "SeriLogTest.Tester" - This is verbose {@tester}

The second log statement outputs:

2014-08-19 10:02:25 [Verbose] This is verbose Tester { Count: 7, Name: "Redmond" } - "Dan Local"

I would expect them both to output the same information, just in a different order as defined by the message template. But as you can see, if you don't put the enriched property last, it is taken over by the provided object to be logged and the second template property is ignored. Is there a way to do this?

Danno
  • 933
  • 4
  • 13
  • 30

2 Answers2

12

In case anyone who stumbles across this is curious about how to output all the available context properties, you can use {Properties} in the output string.

.WriteTo.ColoredConsole(
  outputTemplate: "{Timestamp:HH:mm} [{Level}] {Properties}: {Message}{NewLine}{Exception}")

Prints:

19:40 [Information] {Site="Dan Local"}: Hello
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
11

Output templates are the way to achieve this, i.e.:

    .WriteTo.ColoredConsole(
      outputTemplate: "{Timestamp:HH:mm} [{Level}] {Site}: {Message}{NewLine}{Exception}")

This will print the value of the Site property along with every message; e.g.:

Log.Information("Hello");

Prints:

19:40 [Information] Dan Local: Hello
Nicholas Blumhardt
  • 30,271
  • 4
  • 90
  • 101
  • How would you set this in the appSettings? – Sinaesthetic Jan 10 '16 at 00:33
  • How do you achieve this if the sink you're using doesn't support overriding/specifying output templates? (I'm using the Azure Table Storage sink.) – alastairs Oct 28 '16 at 14:12
  • @alastairs usually the ones without `outputTemplate` support aren't outputting formatted text; may need more info about where you intend the formatted text to go (another question?). Cheers! – Nicholas Blumhardt Oct 30 '16 at 21:31