You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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__AnonymousType03[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:05:22