Azure Application Insights追踪疑问:拆分逻辑、OTLP配置及合并方法
解答:Azure Application Insights 追踪模型与OTLP配置问题
1. 为什么Azure Application Insights将追踪拆分为请求(requests)与依赖(dependencies)?
这是由Application Insights的历史设计与定位决定的:
- AI诞生于OpenTelemetry(OTel)标准化之前,最初的模型就基于"入口请求"和"出口依赖"的二元分类,目的是让用户快速区分应用的核心入口操作(比如HTTP接口调用)和外部依赖调用(比如数据库、第三方API)。
- 本质上,
requests和dependencies都是OTel中的Span,只是AI给它们做了语义分类,并存储在不同的表中。它们共享同一个OperationId(即OTel中的TraceId),逻辑上属于同一个完整追踪,只是物理存储拆分。 - 你提到的
traces表并非存储Span数据,而是用于存储自定义日志追踪(比如TelemetryClient.TrackTrace生成的日志),所以看不到完整的Span链条。
2. 如何配置在Application Insights中查看完整OTLP风格的追踪(非仅异常)?
你的第二种配置方向正确,但需要调整细节并使用AI的分布式追踪视图来查看完整链条:
修正后的OTel配置示例
builder.Services.AddOpenTelemetry() .WithTracing(builder2 => builder2 .AddSource("YourAppName") .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("YourServiceName")) // 确保捕获所有ASP.NET Core请求(包括健康检查等默认被过滤的请求) .AddAspNetCoreInstrumentation(opt => opt.Filter = _ => true) // 确保捕获所有HttpClient调用 .AddHttpClientInstrumentation(opt => opt.FilterHttpRequestMessage = _ => true) // 全采样(测试环境用,生产环境可调整为基于概率的采样) .SetSampler(new AlwaysOnSampler()) .AddAzureMonitorTraceExporter(o => { o.ConnectionString = builder.Configuration["ApplicationInsights:ConnectionString"]; })); var app = builder.Build();
查看完整追踪的步骤
- 登录Azure门户,进入你的Application Insights资源。
- 切换到分布式追踪(Distributed Tracing)页面(而非
traces表查询)。 - 输入某个请求的
OperationId(可从requests表中获取),即可看到完整的Span链条,包含所有请求和依赖节点,这就是OTLP风格的统一追踪视图。
3. 若需将分段信息合并为标准OTLP追踪格式,有哪些简便方法?
方法1:通过Kusto查询合并并导出
在AI的日志查询页面,使用以下KQL查询将requests和dependencies表的数据合并为OTLP兼容的Span结构:
// 合并请求和依赖为OTLP Span格式 union requests, dependencies | project TraceId = OperationId, SpanId = Id, ParentSpanId = iff(isnotempty(ParentId), ParentId, ""), SpanName = Name, SpanKind = iff(Type == "request", "SERVER", "CLIENT"), StartTimeUtc = timestamp, DurationMs = todouble(duration) / 10000, // 转换为毫秒 // 提取常见属性,可根据需求扩展 Attributes = pack( "service.name", cloud_RoleName, "http.method", tostring(customDimensions["http.method"]), "http.url", tostring(customDimensions["http.url"]), "dependency.type", Type ) | order by StartTimeUtc asc
查询结果可导出为JSON,直接兼容OTLP的Span格式。
方法2:使用OpenTelemetry Collector中转
如果需要在应用侧直接生成并导出标准OTLP追踪,可部署OTel Collector,将应用的OTel数据先发送到Collector,再由Collector转发到Application Insights和其他OTel兼容系统:
- 应用侧配置改为使用OTLP Exporter:
.AddOtlpExporter(opt => { opt.Endpoint = new Uri("http://your-collector-host:4317"); }) - 在Collector配置中添加Azure Monitor Exporter,实现同时向AI和其他系统发送数据。
内容的提问来源于stack exchange,提问作者user967710
相关产品推荐
相关产品推荐

