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

Spring Boot Java集成Azure Application Insights:自定义属性与遥测重复问题

Azure Application Insights + OpenTelemetry 导致Request遥测重复的原因及解决办法

重复原因分析

  • 双重遥测采集:Spring Boot中同时启用了Azure Application Insights原生SDK和OpenTelemetry SDK,两者都会自动拦截HTTP请求并生成Request遥测,导致重复记录。
  • 依赖冲突:引入OpenTelemetry后,与原有App Insights依赖存在兼容问题,比如两者都注册了Servlet过滤器或Spring MVC拦截器,各自独立采集请求数据。
  • 配置重叠:同时配置applicationinsights.json和OpenTelemetry的otel.*属性,触发了两套独立的请求采集逻辑。

解决办法

1. 移除原生App Insights SDK依赖

如果已切换到OpenTelemetry,直接移除原有的Azure App Insights相关依赖,仅保留OpenTelemetry及App Insights exporter依赖:

<!-- 移除原生App Insights依赖 -->
<!-- <dependency>
    <groupId>com.microsoft.azure</groupId>
    <artifactId>applicationinsights-spring-boot-starter</artifactId>
</dependency> -->

<!-- 保留OpenTelemetry相关依赖 -->
<dependency>
    <groupId>io.opentelemetry</groupId>
    <artifactId>opentelemetry-spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>io.opentelemetry</groupId>
    <artifactId>opentelemetry-exporter-azure-monitor</artifactId>
</dependency>

2. 禁用原生App Insights自动配置

若需保留部分原生依赖,在application.properties或application.yml中禁用App Insights的自动配置:

# 禁用原生App Insights自动配置
spring.autoconfigure.exclude=com.microsoft.azure.spring.autoconfigure.aai.ApplicationInsightsAutoConfiguration

3. 统一使用OpenTelemetry处理自定义属性

确保所有自定义属性通过OpenTelemetry API添加,避免混合使用原生SDK和OTel API:

import io.opentelemetry.api.trace.Span;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    @GetMapping("/demo")
    public String demo() {
        // 给当前Request Span添加自定义属性
        Span.current().setAttribute("custom.user.id", "12345");
        Span.current().setAttribute("custom.request.type", "demo");
        return "Hello World";
    }
}

4. 清理重叠配置

  • 删除或注释applicationinsights.json中的请求采集配置
  • 仅保留OpenTelemetry相关配置,示例:
otel.resource.attributes=service.name=your-service-name
otel.exporter.azure.monitor.connection-string=your-connection-string
otel.traces.sampler=always_on

验证步骤

部署后查看Azure App Insights的Transactions面板,确认Request记录不再重复,且自定义属性已正确附加到对应遥测中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 02:07:03