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

Serilog-ApplicationInsights Sink:自定义POCO属性未序列化日志问题

问题原因及解决方法

你遇到的问题是因为默认情况下,Serilog在处理消息模板中的复杂对象时,若未明确指定解构逻辑,只会调用对象的ToString()方法,所以ApplicationInsights中只显示了对象的类型名而非序列化后的属性内容。

解决步骤:

1. 修改日志消息模板,明确标记要解构的对象

在日志语句中,给对象参数添加@符号,告诉Serilog需要序列化整个对象的属性:

_logger.Error("user is not active {@userObject}", userObject);

2. (可选)配置Serilog的对象解构规则

如果需要控制对象序列化的嵌套深度、字符串长度或集合元素数量等,可在Serilog配置中添加Destructure相关设置,避免因对象过大导致性能或存储问题:

loggerConfiguration                        
    .Enrich.FromLogContext()
    .Enrich.WithExceptionDetails()
    .Enrich.WithProperty("Application", builder.Configuration.GetValue<string>("Application"))
    .Enrich.WithProperty("Environment", builder.Configuration.GetValue<string>("Environment"))
    // 添加对象解构配置,按需调整参数
    .Destructure.ToMaximumDepth(3) // 设置对象嵌套的最大序列化深度
    .Destructure.ToMaximumStringLength(1000) // 设置字符串属性的最大长度
    .Destructure.ToMaximumCollectionCount(100) // 设置集合属性的最大元素数量
    .WriteTo.ApplicationInsights(services.GetRequiredService<TelemetryConfiguration>(), TelemetryConverter.Traces);

完成以上配置后,userObject的属性就会被扁平化序列化,在ApplicationInsights中以结构化形式展示。

内容的提问来源于stack exchange,提问作者Sai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 00:22:36