什么是Serilog解构? [英] What is Serilog destructuring?
问题描述
Serilog的 @
语法的目的是什么?
What is the purpose of Serilog's @
syntax?
如果我运行以下命令:
var dummy = new { Foo = "Bar", Date = DateTime.Now };
Log.Information("Dummy object: {Dummy}", dummy);
然后我将输出输出到控制台,如下所示:
Then I get an output to the console like so:
Time: 16:20 [Level: Information] (ManagedThreadID: 8) Message: Dummy object: "Foo = Bar, Date = 25/06/2016 16:20:30 }"
如果我将 {Dummy}
更改为 {@ Dummy}
,那么我将得到相同的输出
If I change the {Dummy}
to {@Dummy}
then I get the same output
Time: 16:22 [Level: Information] (ManagedThreadID: 8) Message: Dummy object: Foo: "Bar", Date: 06/25/2016 16:22:28 }
那么, @
应该怎么做?
推荐答案
仔细查看,您会发现它不是相同的输出.
Look closely, and you'll see that it is not the same output.
Dummy前面的 @
运算符告诉Serilog序列化传入的对象,而不是使用 ToString()
对其进行转换,这就是您的第一个示例而不使用 @
运算符.
The @
operator in front of Dummy tells Serilog to serialize the object passed in, rather than convert it using ToString()
, which is what happens on your first example without using the @
operator.
您在第一个示例中的日志事件将以(在JSON中)这样的属性结尾:
Your log event in the first example will end up with a property like (here in JSON):
{
"Dummy": "{ Foo = Bar, Date = 25/06/2016 16:20:30 }"
}
使用{@Dummy}会将参数序列化为结构化数据:
Using {@Dummy} will cause the parameter to be serialized as structured data:
{
"Dummy":
{
"Foo": "Bar",
"Date": "25/06/2016 16:20:30"
}
}
Nicholas Blumhardt的评论(Serilog的创建者):
Comment from Nicholas Blumhardt (creator of Serilog):
在适当情况下,使用
@
运算符对于操作/分析.
Where appropriate, using the
@
operator is much more useful for manipulation/analysis.
之所以选择加入",是因为.NET中的大多数类型程序可以很好地转换为字符串,但不能干净/有意义地可序列化.通过使用@选择序列化,您的意思是:我知道我在做什么,序列化该对象!:)
The reason for this "opt-in" requirement is that most types in .NET programs convert nicely into strings, but aren't cleanly/meaningfully serializable. By opting in to serialization with @ you're saying: "I know what I'm doing, serialize this object!" :)
这篇关于什么是Serilog解构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!