Serilog Network.Sink json 输出格式

Serilog Network.Sink json output format

我一直在使用 Serilog 登录到本地文件,它具有选择输出模板的好用且简单的功能,

像这样:

  _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();

现在我想做的是使用 Serilog 进行网络日志记录,如下所示:

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

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

如果我这样记录:

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

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

            log.Information(json);

kibana 板上的输出如下所示:

{"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}"}

虽然我希望它是我提交的唯一对象:

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

数据发送(或呈现)方式的自定义取决于您使用的接收器,因为它会为您提供执行此操作的方法。

例如,某些接收器允许您提供 outputTemplate 字符串来定义属性,其他接收器允许您提供 class 实现 ITextFormatter 负责格式化消息。

您似乎正在使用 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) 并决定消息的发送方式。