【问题标题】:Writing structured logs with Serilog使用 Serilog 编写结构化日志
【发布时间】:2018-01-24 14:31:55
【问题描述】:

我用 Serilog 尝试了以下日志:

this.logger.Debug("Incoming metrics data {ClientId}", new { clientid = 54732 });

Serilog 产生了这个输出:

Incoming metrics data "{ clientid = 54732 }"

Serilog 是一个结构化的记录器,我预计它会产生这样的结果:

Incoming metrics data {ClientId}, {clientId: 54732}

我做错了什么还是我对 Serilog/结构化日志的理解有误?

【问题讨论】:

    标签: c# .net serilog structured-logging


    【解决方案1】:

    两件事;首先,要序列化这样的结构,您需要使用 结构捕获运算符 @:

    this.logger.Debug("Incoming metrics data {@Client}", new { ClientId = 54732 });
    

    这将捕获传入对象的各个属性,因此重写示例中的事件将具有Client 属性和ClientId 子属性。

    这将为您提供如下输出:

    Incoming metrics data {"ClientId": 54732}
    

    (假设您使用的是最新的 Serilog 控制台接收器和默认模板;其他配置可能无法以 JSON 样式打印嵌入的数据。)

    第二个考虑是事件的完整结构没有显示在 Serilog 的文本输出中 - 这是 Serilog 的“人性化”面孔。如果你想记录结构,你可以像这样插入CompactJsonFormatter(再次假设控制台接收器):

    .WriteTo.Console(new CompactJsonFormatter())
    

    这也适用于文件等 - https://github.com/serilog/serilog-formatting-compact 的详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2021-10-03
      • 1970-01-01
      • 2015-06-09
      相关资源
      最近更新 更多