Serilog消息模板参数中@与$的作用及{@data}和{data}的差异
Serilog日志模板中{@data}与{data}的区别
核心差异在于对象的处理方式:
- 不带@的{data}:仅调用参数对象的
ToString()方法输出结果。如果是自定义类,默认会输出类的完整命名空间+类名;如果重写了ToString(),则返回你定义的文本内容。这种方式只能看到对象的表层描述,无法查看内部属性和嵌套结构。 - 带@的{@data}:触发对象的结构化序列化,会将对象的所有属性、嵌套子对象完整解析成结构化格式(默认是JSON)。日志里会保留对象的完整数据结构,方便排查问题时查看数据的具体细节。
实际输出示例
假设你有一个匿名对象:
var jsonData = new { Id = 123, Name = "User1", Profile = new { Age = 25, Email = "user1@example.com" } };
- 使用
logger.LogError(ex, "Failed to add {data}", jsonData)时,日志消息会类似:Failed to add <>f__AnonymousType0
3[System.Int32,System.String,<>f__AnonymousType12[System.Int32,System.String]] - 使用
logger.LogError(ex, "Failed to add {@data}", jsonData)时,日志消息会类似:Failed to add {"Id":123,"Name":"User1","Profile":{"Age":25,"Email":"user1@example.com"}}
同时,带@的参数会作为结构化属性存入日志,支持后续通过日志系统进行属性筛选、查询等操作,这是纯文本输出做不到的。
内容的提问来源于stack exchange,提问作者Matthew MacFarland
相关产品推荐
相关产品推荐

