Tim Long
Tim Long

Reputation: 13788

In NLog fluent logging, how can I force a log property to be rendered as JSON?

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()?

Upvotes: 1

Views: 594

Answers (0)

Related Questions