1

I'm using NLog to create semantic logs in a Seq server. I want to log an object that has a ToString() method that produces a short human readable summary of the data content. So I want to render the object as a string when formatting it using the message template. I also want to include the object as a log property and have all of its properties rendered as JSON, so that I can examine this data in Seq. So basically I want to log the same object two different ways.

Here's how I'm trying to do this in code:

public async Task AddReading(ISensorReading reading)
  {
  log.Info()
    .Message("add reading {$value}", reading)
    .Property("SensorReading", reading)
    .Write();
  AddToRepository(reading);
  await Task.Delay(reading.TimeToLive.ToTimeSpan(), cancelCleanup.Token)
    .ContinueOnAnyThread();
  RemoveFromRepository(reading);
  }

The first part works fine. The problem is with the .Property() part. This also calls .ToString() on the object and renders it as a string. I want a JSON document instead.

I can get this effect if I use this as my message template:

  .Message("add reading {@value}", reading)

This renders the object as JSON into the log properties, but unfortunately also injects the JSON into the formatted log message, which makes for a pretty unreadable message. How to I get this behaviour when using .Property()?

Tim Long
  • 13,508
  • 19
  • 79
  • 147
  • 1
    Specify `MaxRecursionLimit="1"` for your [JsonLayout](https://github.com/NLog/NLog/wiki/JsonLayout) and it should render the properties just fine without using `@`. – Rolf Kristensen Dec 27 '21 at 09:11
  • @RolfKristensen I don't currently have any JsonLayout, I'm relying on the Seq target to "do the right thing". Perhaps that's an unrealistic expectation. So I should create a JsonLayout entry within my Seq target configuration? However the default for `MaxRexursionLimit` is already 1, according to the documentation. I will try it and see what happens. – Tim Long Dec 28 '21 at 13:23
  • The Seq-Target has `MaxRecursionLimit`-option that you can configure. https://github.com/datalust/nlog-targets-seq/blob/d325b26c0362d8a3fd54d994087d311ee73c05fe/src/NLog.Targets.Seq/SeqTarget.cs#L94 – Rolf Kristensen Dec 28 '21 at 15:47

0 Answers0