简体   繁体   English

使用Serilog编写结构化日志

[英]Writing structured logs with Serilog

I tried the following log with Serilog: 我用Serilog尝试了以下日志:

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

Serilog produced this output: Serilog产生了以下输出:

Incoming metrics data "{ clientid = 54732 }"

Serilog being a structured logger I've expected it to produce something like this: Serilog是结构化的记录器,我期望它会产生以下内容:

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

Am I doing something wrong or am I understanding Serilog/structured-logging wrong? 我做错了什么还是我理解Serilog /结构化日志错误?

Two things; 两件事情; first, to serialize a structure like this you need to use the structure-capturing operator @ : 首先,要序列化这样的结构,您需要使用结构捕获运算符 @

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

This will capture the individual properties of the object passed in, so the event in the rewritten example will have a Client property with ClientId sub-property. 这将捕获传入的对象的各个属性,因此重写示例中的事件将具有带ClientId子属性的Client属性。

This will give you output like: 这将为您提供如下输出:

Incoming metrics data {"ClientId": 54732}

(Assuming you are using the latest Serilog console sink with the default template; other configurations may not print the embedded data JSON-style.) (假设您使用的是默认模板的最新Serilog控制台接收器;其他配置可能无法以JSON样式打印嵌入式数据。)

The second consideration is that the full structure of the event isn't shown in Serilog's text output - it's the "human-friendly" face of Serilog. 第二个考虑因素是该事件的完整结构未在Serilog的文本输出中显示-这是Serilog的“人性化”面孔。 If you want to record structure, you might plug in CompactJsonFormatter like so (again assuming the console sink): 如果要记录结构,则可以像这样插入CompactJsonFormatter (同样假定控制台接收器):

.WriteTo.Console(new CompactJsonFormatter())

This works for files etc., too - details at https://github.com/serilog/serilog-formatting-compact . 这也适用于文件等-有关详细信息, 参见https://github.com/serilog/serilog-formatting-compact

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM