How to serialize logs as json using serilog in kafka?

44 views Asked by At

I am using Serilog kafka in my project. Serilog.Sinks.ConfluentKafka

When I send an object log to logger:

var message = new Message { Name = "x", Age = 1};

logger.LogInformation("{Message}", message);

Writes the message success but it looks like following:

{
  "Timestamp": ...
  "Level": ...
  "Properties": {
     "Message": "Message { Name = "x", Age = 1 }"
  }
}

Wtites message as string.

But I wat to seperate objects in properties of any object like following:

{
  "Timestamp": ...
  "Level": ...
  "Properties": {
     "Message": { 
         Name = "x", 
         Age = 1 
     }
  }
}
1

There are 1 answers

0
Marco Merola On

As specified here: https://github.com/serilog/serilog/wiki/Formatting-Output#formatting-json

Many sinks record log events as JSON, or can be configured to do so. To emit JSON, rather than plain text, a formatter can be specified.

You may want to try serilog-formatting-compact: https://github.com/serilog/serilog-formatting-compact

Then passing it to your serilog-sinks-kafka logger

Log.Logger = new LoggerConfiguration()
              .WriteTo.Kafka(GetTopicName, "localhost:9092",
                    formatter: new CompactJsonFormatter());
              .CreateLogger();