Search code examples
c#.net-coreserilog

Serilog Network.Sink json output format


I've been using Serilog to log to local file and it has nice and easy feature to pick output template,

like this:

  _logger = new LoggerConfiguration()
                  .WriteTo.File(
                      Path.Combine(config.Value.FilePath, config.Value.FileName),
                      outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss}] {Message:lj}{NewLine}",
                      rollingInterval: RollingInterval.Day
                  ).CreateLogger();

And right now what Iam trying to do is to use Serilog for network logging, like this:

    var ip = IPAddress.Parse(config.Value.ServerIp);

        _logger = new LoggerConfiguration()
                  .WriteTo.TCPSink(ip, config.Value.Port)
                  .CreateLogger();

And If I am logging like this:

var message = new { to_index = "test-index", message  = "test-message" };

            var json = JsonConvert.SerializeObject(message, Formatting.Indented);

            log.Information(json);

Output on kibana board will look like :

{"timestamp":"2020-04-11T10:10:58.1110467+02:00","level":"Information","message":"{\r\n  \"to_index\": \"test-index\",\r\n  \"message\": \"test-message\"\r\n}"}

While I would like it to be ONLY object I submitted:

{\"to_index\": \"test-index\",\"message\": \"test-message\"}

Solution

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

    For example, some sinks allow you to provide an outputTemplate string to define the properties, others allow you to provide a class that implements ITextFormatter responsible for formatting the messages.

    It seems you are using Serilog.Sinks.Network which does allow you to provide a custom ITextFormatter, so you can implement your own formatter based on one of the default ones (CompactJsonFormatter.csand RenderedCompactJsonFormatter.cs) and decide how the message should be sent.